Timing Without delay(): Using millis()
See why delay() blocks your program, then use millis() to blink LEDs, read sensors and respond to buttons at the same time without missing input.
Welcome back!
Step 1 of 14Learn
The button that only worked sometimes
Nia's project blinks a warning light once per second and should sound a buzzer immediately when a button is pressed. In testing, the button responds only about half the time.
Her loop looks like this:
digitalWrite(LED_PIN, HIGH); delay(500);
digitalWrite(LED_PIN, LOW); delay(500);
if (digitalRead(BTN) == LOW) tone(BUZZER, 1000, 200);During each delay(500), the processor does nothing else. The button is checked for a split second once per second. A quick press that starts and ends inside a delay is never seen.
delay() is blocking: it stops the whole program. That's fine for Blink, but real projects do several things at once: blink a light, read a sensor, watch a button, update a display. For that you need a non-blocking approach.
The tool is millis(), which returns the number of milliseconds since the board started. It's like checking a clock on the wall instead of falling asleep for a set time. Your loop runs constantly, and each task asks: "Has enough time passed since I last did my thing?"
Step 2 of 14Learn
The millis() pattern
Here's Blink rewritten without delay:
const int LED_PIN = 13;
const unsigned long INTERVAL = 500;
unsigned long previous = 0;
bool ledOn = false;
void setup() { pinMode(LED_PIN, OUTPUT); }
void loop() {
unsigned long now = millis();
if (now - previous >= INTERVAL) {
previous = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn);
}
// other tasks run here, thousands of times per second
}Each pass, the code checks whether 500 ms have passed since the last toggle. If yes, it records the new time and flips the LED. If not, it moves on immediately. Now the button check, a sensor read or a display update can sit below the if block and run constantly.
Three details matter:
- Use unsigned long for anything that stores millis(). An int overflows after about 32.8 seconds.
- Always write now − previous >= INTERVAL. This subtraction still works correctly when millis() wraps back to zero, which happens after about 49.7 days. Comparing
now >= previous + INTERVALbreaks at the wrap. - Each independent task gets its own previous variable and interval.
Step 3 of 14Practice · Fill in the blanks
Fill in the blanks
To check whether an interval has passed, the safe comparison is millis() − >= interval, and the time variables should be of type .
Step 4 of 14Diagram
One pass through a non-blocking loop()
Tap a shape with to see more.
- now = millis()
Read the clock once per pass.
- now − previous ≥ interval?
If not, skip the task and move on immediately.
- Run task, previous = now
Toggle the LED and restart the countdown.
- Check button and other tasks
Because nothing waits, the button is checked on every pass.
Step 5 of 14Practice · Work it out
millis() returns an unsigned long that counts up to 232 − 1 milliseconds before wrapping to zero. About how many days is that? Round to one decimal place.
Step 6 of 14Learn
Two tasks at different speeds
The real payoff comes with several tasks. This sketch blinks an LED every 500 ms and reads a temperature sensor every 2 seconds, while checking a button on every pass:
unsigned long lastBlink = 0, lastRead = 0;
void loop() {
unsigned long now = millis();
if (now - lastBlink >= 500) {
lastBlink = now;
toggleLed();
}
if (now - lastRead >= 2000) {
lastRead = now;
Serial.println(readTemperature());
}
if (digitalRead(BTN) == LOW) {
soundAlarm(); // checked constantly
}
}None of the tasks waits for the others. The loop may run 50,000 times between temperature readings, and the button is checked on every one of them.
This structure scales. Many projects grow into a loop with a dozen timed tasks, each with its own timer. It's the simplest form of cooperative multitasking: each task does a quick bit of work and returns, so everyone gets a turn. The one rule: no task may block for long. A single delay(1000) anywhere freezes all the others.
Step 7 of 14Timeline
Two tasks sharing the first two seconds
- 0 msLED on, temperature read
Both timers start together.
- 500 msLED off
The temperature task is not due yet, so it is skipped.
- 1,000 msLED on
- 1,500 msLED off
- 2,000 msLED on, temperature read
Both tasks fall due on the same pass.
- Every passButton checked
Between the timed events the loop still runs thousands of times, so a press is noticed within a millisecond.
Step 8 of 14Compare
delay() vs. millis()
| Aspect | delay() | millis() pattern |
|---|---|---|
| How it works | Pauses the whole program for a set time | Checks the clock and moves on if it is not time yet |
| Other code during the wait | Nothing else runs (interrupts aside) | Everything else keeps running |
| Code length | Very short | A few more lines and a variable per task |
| Good for | Quick tests, startup pauses, very simple sketches | Any project that must react to input while timing something |
| Typical bug | Missed button presses, sluggish response | Using int instead of unsigned long; forgetting to update the previous time |
Step 9 of 14Note
Step 10 of 14Practice · Diagram
A plant-watering state machine
The pump is running right now. Which state is the sketch in?
Tap the shape that answers the question, then press Check.
- IDLE
Check soil moisture every few seconds. Too dry? Switch on the pump and go to WATERING.
- WATERING
Pump on. After 5 seconds (measured with millis), switch it off and go to WAITING.
- WAITING
Give the water 10 minutes to soak in, then return to IDLE.
Step 11 of 14Practice · True or false
In the millis() pattern, if you forget to set previous = now inside the if block, the task runs once after the interval and then on every loop pass after that.
Step 12 of 14Note
Step 13 of 14Practice · What would you do?
What would you do?
A greenhouse sketch reads a soil sensor every 10 minutes using delay(600000). The owner now wants a manual "water now" button. What should change?
Step 14 of 14Practice · Choose one
Which variable declaration is correct for storing the time a task last ran?
Lesson complete!