Arguments.ino 1.4 KB
Newer Older
1 2 3 4 5 6
/*
 * This example demonstrates used of Ticker with arguments.
 * You can call the same callback function with different argument on different times.
 * Based on the argument the callback can perform different tasks.
 */

B
Bert Melis 已提交
7 8 9
#include <Arduino.h>
#include <Ticker.h>

10 11 12 13 14 15 16
// Arguments for the function must remain valid (not run out of scope) otherwise the function would read garbage data.
int LED_PIN_1 = 4;
#ifdef LED_BUILTIN
  int LED_PIN_2 = LED_BUILTIN;
#else
  int LED_PIN_2 = 8;
#endif
B
Bert Melis 已提交
17 18 19 20

Ticker tickerSetHigh;
Ticker tickerSetLow;

21 22 23 24 25 26 27 28 29 30 31 32 33
// Argument to callback must always be passed a reference
void swapState(int *pin) {
  static int led_1_state = 1;
  static int led_2_state = 1;
  if(*pin == LED_PIN_1){
    Serial.printf("[%lu ms] set pin %d to state: %d\n", millis(), *pin, led_1_state);
    digitalWrite(*pin, led_1_state);
    led_1_state = led_1_state ? 0 : 1; // reverse for next pass
  }else if(*pin == LED_PIN_2){
    Serial.printf("[%lu ms] set pin %d to state: %d\n", millis(), *pin, led_2_state);
    digitalWrite(*pin, led_2_state);
    led_2_state = led_2_state ? 0 : 1; // reverse for next pass
  }
B
Bert Melis 已提交
34 35 36
}

void setup() {
37 38 39 40
  Serial.begin(115200);
  pinMode(LED_PIN_1, OUTPUT);
  pinMode(LED_PIN_2, OUTPUT);
  //digitalWrite(1, LOW);
B
Bert Melis 已提交
41
  
42 43
  // Blink LED every 500 ms on LED_PIN_1
  tickerSetLow.attach_ms(500, swapState, &LED_PIN_1);
B
Bert Melis 已提交
44
  
45 46
  // Blink LED every 1000 ms on LED_PIN_2
  tickerSetHigh.attach_ms(1000, swapState, &LED_PIN_2);
B
Bert Melis 已提交
47 48 49 50 51
}

void loop() {

}