We can delay execution of some functions by using delay() method. There is one significant drawback, delay() ,method pauses the whole system for given time. In most cases it is unacceptable.
That’s why it’s better to use basic timer as in example below. The example shows how to turn on and off LED_BUILTIN IN 1000ms interval with millis() method. Millis() method return the time that has elapsed since start of the program.
int interval = 2000;
long lastTime = 0;
bool isLedOn = false;
void setup()
{
pinMode(LED_BUILTIN, OUTPUT);
}
void ToggleLed()
{
isLedOn = !isLedOn;
digitalWrite(LED_BUILTIN, isLedOn);
}
void loop()
{
long timeElapsed = millis();
if(timeElapsed - interval >= lastTime)
{
lastTime = timeElapsed;
ToggleLed();
}
}