SimpleTimer and Delay() question

Because delay() is blocking (i.e. absolutely nothing else gets done on the MCU until the delay is finished sitting around on it’s backside), It is to be avoided wherever possible for wireless connected projects… else it tends to cause disconnections.

Timers are the answer… yes, it is a bit of extra coding and logic, but it is non-blocking and much more elegant in operation.

BAD :rage:

BLYNK_WRITE(Vx)  // Virtual button on Vx to activate action
{
  int BTN = param.asInt();
    if (BTN == 1) {
      digitalWrite(pin, HIGH);  // Set pin high
      delay(5000); // NOOOOOooooooooo
      digitalWrite(pin, LOW);  // Set pin Low
      }
}

GOOD :heart_eyes:

BLYNK_WRITE(Vx)  // Virtual button on Vx to activate action
{
  int BTN = param.asInt();
  if (BTN == 1) {
    ActionON;  // Run ActionON function
  }
}

void ActionON()
{
  digitalWrite(pin, HIGH);  // Set pin high
  timer.setTimeout(5000L, ActionOFF);  // Run ActionOFF function in 5 seconds
}

void ActionOFF()
{
  digitalWrite(pin, LOW);  // Set pin Low
}

And this is just a dirt simple code solution that is within my coding experience level… there are probably even more elegant ways of coding a non-blocking delay.

EDITED - switched code to setTimeout from setTimer

8 Likes