Tuesday, April 19, 2016

NodeMCU (ESP8266) call function repeatedly in fixed interval, with Ticker.

Ticker is a library of ESP8266 Arduino Core for calling functions repeatedly with a certain period.

It is currently not recommended to do blocking IO operations (network, serial, file) from Ticker callback functions. Instead, set a flag inside the ticker callback and check for that flag inside the loop function.



NodeMCU/ESP8266 example to toggle built-in LED in 0.5 second, using Ticker.
#include <Ticker.h>

Ticker ticker;

boolean ticker_reached;
boolean LED_state;

void ticker_handler(){
  ticker_reached = true;
}

void setup() {
  pinMode(LED_BUILTIN, OUTPUT);
  
  ticker_reached = false;
  LED_state = HIGH;

  //call ticker_handler() in 0.5 second
  ticker.attach(0.5, ticker_handler);
  
}

void loop() {

  if(ticker_reached){
    ticker_reached = false;
    digitalWrite(LED_BUILTIN, LED_state);
    LED_state = !LED_state;
  }

}


No comments:

Post a Comment