arduino Time Management Non-blocking blinky with the elapsedMillis library (and class)


Example

The elapsedMillis library provides a class with the same name that keeps track of the time that passed since it was created or set to a certain value:

#include <elapsedMillis.h>

#define OUTPIN LED_BUILTIN
#define PERIOD 500

elapsedMillis ledTime;

bool ledState = false;

void setup() 
{                
  // initialize the digital pin as an output.
  pinMode(OUTPIN, OUTPUT);     
}

void loop()
{
    if (ledTime >= PERIOD) 
    {                
        ledState = !ledState;
        digitalWrite(OUTPIN, ledState);
        ledTime = 0;
    }
    // do other stuff here
}

You can see in the example that the ledTime object is assigned zero when the LED pin was toggled. This might not be surprising at first glance, but it has an effect if more time-consuming things are happening:

Consider a situation where the comparison between ledTime and PERIOD is done after 750 milliseconds. Then setting ledTime to zero means that all following toggle operations will be 250 ms "late". If, in contrast, PERIOD was subtracted from ledTime, the LED would see one short period and then continue blinking as if nothing happened.