The first code you write on an Arduino usually contains delay(). That's fine for Blink. But as soon as you try to do two things together (an LED blinking and a button being read), you'll discover that delay stops everything.
The problem
void loop() {
digitalWrite(13, HIGH); delay(1000);
digitalWrite(13, LOW); delay(1000);
if (digitalRead(2) == LOW) { /* button */ }
}
The button will be read once every two seconds. If you press and release in the middle of the delay, the program won't even know.
Inside, delay is an empty loop: the microcontroller counts until the time is up, and does nothing else. (Only interrupts run in the background, which is the subject of the interrupts article.)
The fix: look at the clock
millis() returns the number of milliseconds since the board started. So instead of "waiting", you look at the clock: "Has a second passed since last time? If yes, do the thing. If not, carry on".
Like putting food in the oven and glancing at the clock now and then while you do other things, instead of standing in front of the oven for an hour.
unsigned long lastBlink = 0;
bool ledOn = false;
void loop() {
if (millis() - lastBlink >= 1000) {
lastBlink = millis();
ledOn = !ledOn;
digitalWrite(13, ledOn);
}
if (digitalRead(2) == LOW) {
// the button is read all the time
}
}
The loop now runs thousands of times a second, and each task runs at its own time.
Several tasks at different intervals
unsigned long tLed = 0, tSensor = 0;
void loop() {
unsigned long now = millis();
if (now - tLed >= 500) { tLed = now; /* blink the LED */ }
if (now - tSensor >= 2000) { tSensor = now; /* read the sensor */ }
}
You can add any number of tasks the same way. The only rule: none of them may wait. Each does its work quickly and gets out.
A different on time and off time
An LED that's on for 100 ms and off for 900 (a short flash like alarm systems):
unsigned long tFlash = 0;
bool on = false;
void loop() {
unsigned long wait = on ? 100 : 900;
if (millis() - tFlash >= wait) {
tFlash = millis();
on = !on;
digitalWrite(13, on);
}
}
The idea: the time you wait for changes with the current state.
A traffic light: states (a state machine)
When you have a sequence of steps with different durations, write it as states: the program remembers which step it's on, and each step has its duration and the step after it.
enum State { GREEN, YELLOW, RED };
State st = GREEN;
unsigned long tState = 0;
void setLights(bool g, bool y, bool r) {
digitalWrite(5, g); digitalWrite(6, y); digitalWrite(7, r);
}
void loop() {
unsigned long now = millis();
switch (st) {
case GREEN:
setLights(1, 0, 0);
if (now - tState >= 5000) { st = YELLOW; tState = now; }
break;
case YELLOW:
setLights(0, 1, 0);
if (now - tState >= 2000) { st = RED; tState = now; }
break;
case RED:
setLights(0, 0, 1);
if (now - tState >= 5000) { st = GREEN; tState = now; }
break;
}
// here you can read a pedestrian button or a sensor without being stuck
}
In the same way, a pedestrian button can change the state at any moment, which was impossible with delay.
A timeout
Sometimes you wait for a reply from a module or sensor. If the reply doesn't come, don't keep waiting forever:
unsigned long start = millis();
while (!Serial2.available()) {
if (millis() - start > 2000) {
Serial.println("the module didn't reply");
break;
}
}
This solves the "program hangs when the sensor is disconnected" problem, which you can spot with the Serial Monitor.
Steady timing
lastBlink = millis() counts from the moment of execution. If the loop runs 3 ms late, the next time is also 3 ms late, and the delay accumulates. If timing matters (a clock or a counter):
if (millis() - lastTick >= 1000) {
lastTick += 1000; // instead of lastTick = millis()
seconds++;
}
That keeps the schedule steady however late the loop runs. But note: if the program stalls for a long time, this method will run the task several times in a row to "catch up".
The overflow: don't worry
The counter reaches its maximum and wraps to zero after about 49.7 days. If you write the condition with subtraction as above (millis() - last >= interval), the calculation stays correct even when it wraps to zero, because of how unsigned numbers are calculated.
A worked example: the maximum value is 4,294,967,295. If last was 4,294,967,000, and then the counter wrapped so that now = 200, the subtraction now - last comes out as 496, which really is the time that passed (296 up to the wrap + 200 after). unsigned numbers wrap like a car's odometer.
The wrong way, which can break at that moment: if (millis() >= nextTime), because nextTime can wrap before millis() does, so the condition is met immediately.
Always make the variables unsigned long. If you use int, it wraps after only 32 seconds.
micros() for short times
Exactly the same idea, but in microseconds, and it wraps about every 70 minutes. Useful for measuring a pulse width or the time between two pulses, such as calculating speed in the Hall sensor article. On the Uno its resolution is 4 microseconds.
When is delay still acceptable?
- Very short delays (microseconds or a few milliseconds) in communication steps with modules.
- A program that really does only one thing.
- In
setup()for a one-off wait at the start.
On the ESP32, delay doesn't waste the processor as on the Uno: it hands it to system tasks (Wi-Fi, for example). But your loop is still stopped, so the same advice applies to your code.
Quick comparison
| delay() | millis() | |
|---|---|---|
| Ease | One line | Needs a variable and a condition |
| The program while waiting | Stopped | Running and doing other things |
| Several tasks at different times | Very hard | Easy |
| Responding to a button | Late or missed | Almost instant |
The next step
If you need an instant response to a very fast event (pulses or an encoder), see interrupts. And if the button is read more than once per press, see debouncing, which is also done with millis.
FAQ
The program got messy as the tasks multiplied? Put each task in its own function (blinkTask(), sensorTask()) and call them from the loop. The code will be much clearer.
Are there libraries that do this? Yes, such as TaskScheduler and others. But understand the manual method first, because it's what you'll use to fix any problem.