Sub topic 5
Measuring Time with `millis()`
Prerequisites and the timing model
This chapter assumes you know the structure of an Arduino sketch and can use setup(), loop(), pinMode(), and digitalWrite(). You should also be comfortable with if statements, Boolean values, and integer types in C++.
millis() is an Arduino function that returns the number of milliseconds since the board started running the current sketch. A millisecond is one thousandth of a second. The return value increases while your sketch runs.
unsigned long startTime = millis();The value is stored in an unsigned long, an integer type that can represent only non-negative values. On common 32-bit Arduino timing implementations, the counter eventually reaches its largest value and wraps back to zero. This happens after about 49.7 days.
The important idea is to store a previous timestamp and compare elapsed time:
unsigned long now = millis();
if (now - startTime >= interval) {
// The interval has elapsed.
}The expression now - startTime gives the time that has passed since startTime. It does not pause the processor.
Why not use `delay()`?
delay(500) waits for 500 milliseconds, but the sketch cannot do normal work during that wait. This makes a button less responsive and prevents other timed tasks from running.
With millis(), loop() continues repeatedly. Each pass checks whether enough time has elapsed. Other work can run on passes where the interval has not elapsed.
| Technique | During the wait | Suitable for several tasks |
|---|---|---|
| `delay(500)` | The sketch is blocked | No |
| `millis()` comparison | The sketch keeps running | Yes |
Building a non-blocking timer
The following sketch toggles the built-in LED approximately every 500 milliseconds. It does not use delay(), so additional work can be placed in loop().
const unsigned long INTERVAL_MS = 500;
unsigned long previousMillis = 0;
bool ledState = LOW;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= INTERVAL_MS) {
previousMillis = now;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
// Other work can run here on every pass through loop().
}At startup, previousMillis is zero. Once the current time is at least 500 milliseconds, the condition becomes true. The sketch records the current time, changes the LED state, and continues checking.
Assigning previousMillis = now measures the next interval from the moment the action actually occurred. This is simple and prevents a long delay in one loop pass from causing many immediate catch-up actions. For a task that must keep a precise schedule, you can instead use previousMillis += INTERVAL_MS, but that may cause repeated catch-up actions after a long interruption.
Handling counter rollover
Do not compare a future deadline like this:
// Fragile across millis() rollover:
if (millis() >= startTime + timeout) {
// timeout has elapsed
}The addition can wrap around and produce a small value. Use unsigned subtraction instead:
const unsigned long timeout = 1000;
unsigned long startTime = millis();
void loop() {
if (millis() - startTime >= timeout) {
// timeout has elapsed
}
}Unsigned arithmetic is defined to wrap around. When the counter goes from its maximum value to zero, the subtraction still produces the correct elapsed duration, provided the interval is shorter than half the counter’s full range.
Exercise
Why is millis() - startTime >= timeout safer than millis() >= startTime + timeout?
Show answer
Unsigned subtraction remains correct when the millis() counter wraps from its maximum value back to zero. A precomputed future deadline can wrap and become a small number, causing the comparison to fire too early.