Sub topic 11
Blinking without blocking: `millis()`
This chapter assumes you understand Arduino’s setup() and loop() functions, digital output with pinMode() and digitalWrite(), and a basic delay()-based blink. You should also know what a variable is and have an Arduino-compatible board connected to the Arduino IDE.
Why `delay()` blocks the program
A call such as delay(500) pauses the sketch for 500 milliseconds. During that pause, the board does not run the rest of your loop() code. The processor is still active, but your sketch cannot respond to a button, read a sensor, or update another output until the delay ends.
This is called blocking. Blocking is acceptable for a simple first blink, but it becomes a problem when one sketch must perform several tasks.
The millis() function provides a different approach. It returns the number of milliseconds since the board started running the current sketch. Instead of waiting, the sketch repeatedly checks whether enough time has passed.
| Timing method | What the sketch does | Effect on other code |
|---|---|---|
| `delay()` | Waits for a fixed period | Other sketch code is blocked |
| `millis()` | Checks elapsed time during each loop | Other code can run |
Comparing elapsed time
Store the time when the LED last changed. On each pass through loop(), read the current time and subtract the stored time.
const uint8_t LED_PIN = 8;
const unsigned long INTERVAL_MS = 500;
unsigned long previousToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousToggle >= INTERVAL_MS) {
previousToggle = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
// Other code can run here without waiting for the blink.
}previousToggle records the time of the last toggle. now records the current time. The if statement changes the LED only when the elapsed time reaches INTERVAL_MS.
The expression ledOn = !ledOn reverses the Boolean value. If ledOn is false, it becomes true. If it is true, it becomes false. The conditional expression then writes HIGH when the LED should be on and LOW when it should be off.
The loop runs very quickly between toggles. It can therefore perform other work in the space where delay() would have stopped the sketch.
Why the subtraction form matters
Use this form:
if (now - previousToggle >= INTERVAL_MS) {
// The interval has elapsed.
}Do not normally write this:
if (now >= previousToggle + INTERVAL_MS) {
// This can fail after millis() wraps around.
}The return value from millis() is an unsigned long. On common Arduino boards, that value eventually reaches its maximum and wraps back to zero. This is called rollover. The subtraction method continues to work across rollover when the interval is small enough and the time values use an unsigned type.
Use an unsigned type for both time values. Do not replace unsigned long with a signed integer such as int, which may overflow much sooner and can produce incorrect comparisons.
Timing choices and drift
The example sets previousToggle = now after each change. This is simple and works well when the rest of loop() runs quickly. If another task occasionally takes a long time, the next interval begins when the delayed toggle occurs.
For a steadier schedule, advance the previous timestamp by the interval:
previousToggle += INTERVAL_MS;This preserves the intended schedule more closely, but it needs extra handling if the sketch falls far behind. For most beginner and intermediate projects, recording now is easier to understand and sufficient.
A non-blocking blink does not make every task non-blocking automatically. Avoid long loops, long delays, and functions that wait for external input. Each task should check its own timer and return quickly.
Practice
Change INTERVAL_MS to 1000. The LED will change state every second, so one complete on-and-off cycle will take about two seconds.
Then add another periodic task. For example, use a second interval variable and print a message with Serial.println() when that interval elapses. Neither task should call delay().
Exercise
Why does the millis() version let a button-reading task run while the LED is blinking?
Show answer
The loop does not wait for the interval to finish. It checks the elapsed time and immediately continues to the other code when the LED is not due to toggle.