|
| 1 | +/* |
| 2 | + * This example demonstrates used of Ticker with arguments. |
| 3 | + * You can call the same callback function with different argument on different times. |
| 4 | + * Based on the argument the callback can perform different tasks. |
| 5 | + */ |
| 6 | + |
1 | 7 | #include <Arduino.h>
|
2 | 8 | #include <Ticker.h>
|
3 | 9 |
|
4 |
| -// attach a LED to GPIO 21 |
5 |
| -#define LED_PIN 21 |
| 10 | +// Arguments for the function must remain valid (not run out of scope) otherwise the function would read garbage data. |
| 11 | +int LED_PIN_1 = 4; |
| 12 | +#ifdef LED_BUILTIN |
| 13 | + int LED_PIN_2 = LED_BUILTIN; |
| 14 | +#else |
| 15 | + int LED_PIN_2 = 8; |
| 16 | +#endif |
6 | 17 |
|
7 | 18 | Ticker tickerSetHigh;
|
8 | 19 | Ticker tickerSetLow;
|
9 | 20 |
|
10 |
| -void setPin(int state) { |
11 |
| - digitalWrite(LED_PIN, state); |
| 21 | +// Argument to callback must always be passed a reference |
| 22 | +void swapState(int *pin) { |
| 23 | + static int led_1_state = 1; |
| 24 | + static int led_2_state = 1; |
| 25 | + if(*pin == LED_PIN_1){ |
| 26 | + Serial.printf("[%lu ms] set pin %d to state: %d\n", millis(), *pin, led_1_state); |
| 27 | + digitalWrite(*pin, led_1_state); |
| 28 | + led_1_state = led_1_state ? 0 : 1; // reverse for next pass |
| 29 | + }else if(*pin == LED_PIN_2){ |
| 30 | + Serial.printf("[%lu ms] set pin %d to state: %d\n", millis(), *pin, led_2_state); |
| 31 | + digitalWrite(*pin, led_2_state); |
| 32 | + led_2_state = led_2_state ? 0 : 1; // reverse for next pass |
| 33 | + } |
12 | 34 | }
|
13 | 35 |
|
14 | 36 | void setup() {
|
15 |
| - pinMode(LED_PIN, OUTPUT); |
16 |
| - digitalWrite(1, LOW); |
| 37 | + Serial.begin(115200); |
| 38 | + pinMode(LED_PIN_1, OUTPUT); |
| 39 | + pinMode(LED_PIN_2, OUTPUT); |
| 40 | + //digitalWrite(1, LOW); |
17 | 41 |
|
18 |
| - // every 25 ms, call setPin(0) |
19 |
| - tickerSetLow.attach_ms(25, setPin, 0); |
| 42 | + // Blink LED every 500 ms on LED_PIN_1 |
| 43 | + tickerSetLow.attach_ms(500, swapState, &LED_PIN_1); |
20 | 44 |
|
21 |
| - // every 26 ms, call setPin(1) |
22 |
| - tickerSetHigh.attach_ms(26, setPin, 1); |
| 45 | + // Blink LED every 1000 ms on LED_PIN_2 |
| 46 | + tickerSetHigh.attach_ms(1000, swapState, &LED_PIN_2); |
23 | 47 | }
|
24 | 48 |
|
25 | 49 | void loop() {
|
|
0 commit comments