You are on page 1of 2

1 #include <Ticker.

h>
2
3 void func() {
4 Serial.println("func.");
5 }
6
7 Ticker ticker1(func, 1000, 0, MILLIS);
8
9 // Simple class with (non static) method
10 class A {
11 public:
12 A(bool flag) : flag(flag) {}
13
14 void func() {
15 Serial.printf("A::func: %s.\n", flag ? "true" : "false");
16 }
17 bool flag;
18 };
19
20 A a1(true);
21
22 // use lambda to capture a1 and execute a1.func()
23
24 Ticker ticker2([](){a1.func();}, 1000, 0, MILLIS);
25
26 A a2(false);
27
28 Ticker ticker3([](){a2.func();}, 1000, 0, MILLIS);
29
30 // Class that registers its own method as a callback when it's instantiated.
31 class B {
32 public:
33 B(bool flag) : flag(flag), ticker{[this](){this->func();}, 1000, 0, MILLIS} {
34 ticker.start();
35 }
36
37 void func() {
38 Serial.printf("B::func: %s.\n", flag ? "true" : "false");
39 }
40 bool flag;
41 Ticker ticker;
42 };
43
44 B b(true);
45
46 // Class that acts like a function (functor)
47 class C {
48 public:
49 C(int num) : num(num){}
50
51 // you can call an instance directly with parenthesis and this is executed
52 void operator()() const {
53 Serial.printf("C(): %d.\n", num);
54 }
55 int num;
56 };
57
58 C c(4);
59
60 Ticker ticker4(c, 1000, 0, MILLIS);
61
62 void setup() {
63 Serial.begin(115200);
64 delay(1000);
65 Serial.println();
66
67 ticker1.start();
68 ticker2.start();
69 ticker3.start();
70 ticker4.start();
71 }
72
73 void loop() {
74 ticker1.update();
75 ticker2.update();
76 ticker3.update();
77 b.ticker.update();
78 ticker4.update();
79 }
80

You might also like