Menu
CoddyTech

Blink Without Delay

Part of the Timing Without Delay section of Coddy's Arduino journey. Lesson 3 of 18.

delay() stops the whole sketch. While a blink waits its 500 ms, nothing else in loop() runs: a button pressed in that time is not seen until the wait is over.

The fix is to never wait. Let loop() run again and again, very fast, and each time compare the clock with the moment the LED last changed. Until 500 ms have passed, do nothing. Then change the LED and store the new moment:

const unsigned long interval = 500;
unsigned long previousMillis = 0;   // when the LED last changed

void loop() {
  unsigned long now = millis();
  if (now - previousMillis >= interval) {
    previousMillis = now;           // remember this moment
    // switch the LED here
  }
  // anything else here runs thousands of times a second
}

now - previousMillis is the time since the last change. To switch the LED, keep its state in a variable, int redState = LOW;, flip it with if/else and write it with digitalWrite(redLed, redState);.

Forget to update previousMillis and the condition stays true after the first 500 ms, so the LED changes on every loop and looks half lit.

challenge icon

Challenge

Medium

The yellow LED should follow the button, but it reacts late because the red LED's delay() calls stop the loop. Rewrite the red blink with millis():

  • keep the button part as it is
  • every 500 ms, switch the red LED on pin 13
  • no delay() anywhere

Press Run, hold the button and watch both LEDs, then Check.

Try it yourself

const int redLed = 13;
const int yellowLed = 12;
const int buttonPin = 2;

void setup() {
  pinMode(redLed, OUTPUT);
  pinMode(yellowLed, OUTPUT);
  pinMode(buttonPin, INPUT_PULLUP);
}

void loop() {
  // The yellow LED follows the button. Keep this part.
  if (digitalRead(buttonPin) == LOW) {
    digitalWrite(yellowLed, HIGH);
  } else {
    digitalWrite(yellowLed, LOW);
  }

  // The red LED blinks, but each delay() stops the lines above
  // for half a second. Rewrite this part with millis().
  digitalWrite(redLed, HIGH);
  delay(500);
  digitalWrite(redLed, LOW);
  delay(500);
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Timing Without Delay

Practice on your own: Arduino playground