The first Arduino sketch most people write blinks an LED with delay(). It works, until you want the board to do two things at once. This guide explains why, and how millis() fixes it.
The problem with delay()
void loop() {
digitalWrite(LED_BUILTIN, HIGH);
delay(1000);
digitalWrite(LED_BUILTIN, LOW);
delay(1000);
}
delay(1000) pauses the sketch for 1,000 milliseconds. During that time, as Arduino's own reference puts it, no other reading of sensors, calculations or pin changes can happen. If you also want to read a button, it only gets checked once every two seconds, so short presses are missed.
A few things do carry on during a delay, because it doesn't turn off interrupts: incoming serial data is still received, PWM outputs from analogWrite() keep running, and interrupt handlers still run.
What millis() gives you
millis() returns the number of milliseconds since the board started running the sketch, as an unsigned long. Instead of stopping and waiting, you check the clock each time round loop() and only act when enough time has passed. loop() keeps running thousands of times a second, so the sketch can check other things in between.
Blink two LEDs and read a button
This sketch blinks one LED every 500 ms and another every 1,300 ms, and reports button presses straight away. Wire each LED with a resistor (see the LED resistor calculator) to pins 12 and 13, and a push button from pin 2 to GND.
const int LED_A = 12;
const int LED_B = 13;
const int BUTTON = 2;
const unsigned long INTERVAL_A = 500; // ms
const unsigned long INTERVAL_B = 1300; // ms
unsigned long lastA = 0;
unsigned long lastB = 0;
bool stateA = false;
bool stateB = false;
const unsigned long DEBOUNCE = 30; // ms
int lastReading = HIGH;
int buttonState = HIGH;
unsigned long lastChange = 0;
void setup() {
pinMode(LED_A, OUTPUT);
pinMode(LED_B, OUTPUT);
pinMode(BUTTON, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - lastA >= INTERVAL_A) {
lastA += INTERVAL_A;
stateA = !stateA;
digitalWrite(LED_A, stateA);
}
if (now - lastB >= INTERVAL_B) {
lastB += INTERVAL_B;
stateB = !stateB;
digitalWrite(LED_B, stateB);
}
int reading = digitalRead(BUTTON);
if (reading != lastReading) { // input changed (or bounced)
lastChange = now;
lastReading = reading;
}
if (now - lastChange >= DEBOUNCE && reading != buttonState) {
buttonState = reading; // steady for 30 ms: accept it
if (buttonState == LOW) {
Serial.println("Button pressed");
}
}
}
We tested this logic on a PC against a simulated clock and a bouncing button: the LEDs toggled exactly every 500 ms and 1,300 ms, a press with 8 ms of contact bounce printed once, and a 5 ms glitch was ignored.
How it works
- Each task has its own "last time" variable and interval, so you can add as many as you like.
lastA += INTERVAL_Amoves the schedule on by exactly one interval, so the timing doesn't drift even if a loop runs late.lastA = nowalso works, but small delays add up over time.INPUT_PULLUPturns on the pin's internal pull-up resistor, so the pin readsHIGHnormally andLOWwhen the button connects it to GND. No external resistor needed.- Button contacts bounce for a few milliseconds when pressed. The debounce code only accepts a new state once the input has been steady for 30 ms, so one press gives one message.
The 49.7-day rollover
millis() is a 32-bit unsigned number, so it counts up to 4,294,967,295 ms, about 49.7 days, then wraps back to 0. Write your comparisons as a subtraction and this doesn't matter:
if (now - lastA >= INTERVAL_A) // correct: works across the rollover
if (now >= lastA + INTERVAL_A) // wrong: breaks near the rollover
Unsigned subtraction wraps too, so now - lastA is always the true time since lastA, even if the counter has gone back to zero in between. The addition form fails when lastA + INTERVAL_A wraps past zero: now is then bigger than the result straight away. In our simulated test across the rollover, the wrong version toggled the LED on almost every pass of loop() for nearly 0.3 seconds, nearly 300 times, while the subtraction version kept perfect time.
Common mistakes
- Using
intfor times. On an Uno, anintis 16 bits and overflows after 32,767 ms. Arduino's reference warns to useunsigned longfor anything holdingmillis(). - Expecting exact milliseconds. On 16 MHz AVR boards like the Uno,
millis()ticks every 1.024 ms and occasionally jumps by 2 to stay in step. For short, precise timing usemicros(), which wraps after about 71.6 minutes. - Hiding a delay somewhere else. One
delay()or a slow library call anywhere inloop()holds up every task.
For bigger projects, the same idea grows into a "state machine", where each part of the program remembers what it's doing and checks the clock instead of waiting. See the Arduino Uno pinout for which pins to use.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.