Blink without delay for 5 times every 20 seconds I'm trying to write a blink without delay code that will wait 20 seconds, then blink 5 times, then wait another 20 seconds - rinse and repeat.

Here's the minimal code I wrote:

if (currentTime % 20000 == 0) {
  for (int x = 0; x &lt;= 5; x++) {
    if (currentTime % 500 == 0) {
      if (solenoid == LOW) {
        solenoid = HIGH;
      }   else {
        solenoid = LOW;
      }
      digitalWrite(solenoidpin, solenoid);
    }
  }
}
}


All this seems to do is set solenoid to HIGH and keep it there. If I get rid of the for loop and the second if statement, I can get it to switch between low and high every 20 seconds, but adding the if and for loops seems to kill it. Any thoughts on how to make this work?
Here is a solution:

void setup()
{
    Serial.begin(9600);
    pinMode(LED_BUILTIN, OUTPUT);
}

#define INTERVAL 20000L
#define BLINK_TIMES 5
void loop()
{
    static unsigned long lastBlink = 0;
    static int count = 0;

    unsigned long now = millis();

    if(count &gt; 0) {
        count -= blink();
        lastBlink = now;
    } else {
        if(now - lastBlink &gt;= INTERVAL) {
            count = BLINK_TIMES;
        }
    }
}

/*
 * Do one blink.
 * Return 1 when blink is done.
 */
int blink()
{
  static unsigned long lastFlip = 0;
  static int count = 0;
  bool last = false;

  unsigned long now = millis();

  if(now - lastFlip &gt;= 500) {
    digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
    Serial.print(now / 1000); Serial.print(". "); Serial.println("blink");
    lastFlip = now;
    count++;
    if (count == 2) {
      count = 0;
      last = true;
      }
   }

   return (last) ? 1 : 0 ;
}


The count variable controls when to blink and how many times. While it's zero, no blinking.

When not blinking, it keeps comparing actual time with the last time it blinked. When the time exceed 20s, it puts count to five, and in the next loop, the blinking start.

Variables are declared static so they keep their values between loop executions.