Sub topic 13
Timing without `delay()` using `millis()`
Prerequisites and the timing model
This chapter assumes that you can open, verify, and upload an Arduino sketch. You should also know how to connect an LED with a resistor and how setup() and loop() work.
delay() pauses the entire sketch. While the Arduino waits, it cannot read a button, update a display, or check a sensor. This is called blocking behavior.
The millis() function returns the number of milliseconds since the board started running the current sketch. Instead of waiting, your program repeatedly checks how much time has passed.
A non-blocking LED blink
The sketch below changes the built-in LED every 500 milliseconds. The loop continues running during the interval, so other code can run on every pass.
const byte ledPin = LED_BUILTIN;
const unsigned long interval = 500;
unsigned long previousMillis = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= interval) {
previousMillis = now;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
// This work runs on every pass through loop().
Serial.println("The loop is still running");
}previousMillis records when the LED last changed. Each pass calculates the current time in now. When the elapsed time reaches interval, the program toggles the LED.
The ! operator means “not.” Therefore, !ledOn changes true to false or false to true. The conditional operator ? : chooses HIGH when ledOn is true and LOW when it is false.
Why subtraction is safer than comparison
Use this pattern:
if (now - previousMillis >= interval) {
// The interval has passed.
}Do not usually write this:
if (now >= previousMillis + interval) {
// This can fail when millis() rolls over.
}millis() uses an unsigned counter with a limited range. After many days, the counter wraps back to zero. Unsigned subtraction continues to produce the correct elapsed duration for normal timing intervals, even across that rollover. Use unsigned long for values returned by millis() and for time intervals.
Scheduling several tasks
A responsive sketch can keep separate timestamps for separate jobs:
const unsigned long ledInterval = 500;
const unsigned long reportInterval = 1000;
unsigned long lastLedChange = 0;
unsigned long lastReport = 0;
bool ledState = false;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - lastLedChange >= ledInterval) {
lastLedChange = now;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
if (now - lastReport >= reportInterval) {
lastReport = now;
Serial.println("One second passed");
}
// Read buttons and sensors here without waiting.
}Each if is independent. A slow task should not prevent another task from running.
Common errors
- Declaring a time value as
int, which is too small for normal millisecond timing on many Arduino boards. - Calling
millis()once insetup()and never updating the current time. - Putting
delay()inside a supposedly non-blocking section. - Using one timestamp for unrelated tasks, which makes their schedules interfere.
- Forgetting to initialize the pin with
pinMode()before writing to it.
Exercise
Change the two-task sketch so that the LED changes every 250 milliseconds and the serial message prints every 2000 milliseconds. Which variables must change?
Show answer
Change ledInterval to 250 and reportInterval to 2000. The timestamp variables and the timing logic can remain the same.