Sub topic 5
Measuring Time with millis()
This chapter covers the working model of millis(), the Arduino function that reports elapsed time. It also covers the errors that show up most often when people first use it. It assumes you can write a basic sketch with setup() and loop(), use pinMode(), digitalRead() and digitalWrite(), and read C++ if statements, bool variables and integer types. The previous chapter showed why delay() freezes a sketch. Here you replace it with a clock you can read at any moment.
What millis() gives you
millis() returns the number of milliseconds since the board started running the current sketch. The value is an unsigned long, a 32-bit unsigned integer on AVR boards such as the Uno and on ARM boards such as the Zero and Due. It starts at 0 on power-up or reset and increases by one every millisecond.
Calling millis() does not pause anything. It reads a counter and returns right away. This is the key difference from delay(). delay(500) spends 500 ms doing nothing. millis() costs almost no time and lets you decide when to act.
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.println(millis());
delay(1000);
}This sketch prints roughly 0, 1000, 2000 and so on. It uses delay() only to keep the output readable. The value is not exactly a multiple of 1000, because printing takes time too.
The core idea: timestamps and elapsed time
A clock on the wall tells you the time. It does not tell you when to leave. To know when to leave, you note the time when something starts and compare it with the time now. The difference is the elapsed time.
The pattern has three parts:
- Store a timestamp when an event happens, such as a button change or the last blink.
- On every pass through
loop(), readmillis()again. - Subtract the stored timestamp from the current time. If the result is at least your interval, act and store a new timestamp.
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().
}On most passes the if is false and loop() returns at once. That is what keeps the sketch responsive. Anything placed after the if runs thousands of times per second.
Why you compare a difference
You might be tempted to compute a deadline once and compare against it:
unsigned long deadline = millis() + 500;
// later:
if (millis() >= deadline) { /* ... */ }This works for the first 49 days or so and then fails in a confusing way. The counter is 32 bits wide, so it wraps back to 0 after about 49.7 days (2^32 ms). If millis() + 500 lands above the largest 32-bit value, the sum wraps to a small number, and the comparison becomes true immediately. The next chapter covers rollover in detail. For now, adopt the habit that avoids the problem:
// Correct: unsigned subtraction gives the right elapsed time even after millis() wraps to 0.
if (millis() - startTime >= timeout) {
// timeout has elapsed
}Both operands must be unsigned. Store timestamps as unsigned long, never as int or long.
Choosing the right type
The type of your timestamp variable matters more than it looks.
| Declaration | Range | Result |
|---|---|---|
| `unsigned long t` | 0 to 4,294,967,295 | Correct. Matches the return type of `millis()`. |
| `long t` | about ±2.1 billion | Wrong after about 24.9 days, when the value exceeds the signed range. |
| `unsigned int t` | 0 to 65,535 on AVR | Wrong. Truncates the value and wraps every 65.5 seconds. |
| `int t` | -32,768 to 32,767 on AVR | Wrong. Overflows after 32.7 seconds. |
On AVR boards int is 16 bits, so a sketch with int lastTime = millis(); seems to work during a short test and then misbehaves after half a minute. This is one of the most common bugs in beginner millis() code. Compile with warnings enabled to catch the narrowing conversion.
Interval constants are best declared as const unsigned long. If you write const int INTERVAL = 60000; on an AVR board, the value does not fit in a 16-bit int and you get a negative number.
Read the clock once per pass
In the example above, now is read once at the top of loop() and reused. This is better than calling millis() in every comparison, for two reasons.
- Consistency. If you call
millis()twice in one pass, the two values can differ by a millisecond or more. Two tasks that should agree on the current time then disagree. - Clarity. A single
nowmakes each task's timing easy to read and test.
void loop() {
unsigned long now = millis(); // one snapshot for this pass
if (now - lastA >= 200) { lastA = now; /* task A */ }
if (now - lastB >= 1000) { lastB = now; /* task B */ }
}Resolution and accuracy
millis() has a resolution of 1 ms, but this does not mean your action happens exactly on schedule. Three limits apply.
- Granularity of the check. Your code only compares the time when
loop()reaches theif. If another part ofloop()takes 20 ms, a 500 ms action can fire up to 20 ms late. - Timer behavior on AVR. The Uno's timer ticks about every 1.024 ms and the core corrects the count periodically. As a result the returned value occasionally skips a number. Do not test for an exact value such as
millis() == 1000. Always use>=with a difference. - Clock source. Boards that use a ceramic resonator, such as many Uno-compatible boards, can drift by about 0.5% or more. A quartz crystal is more accurate. For long-term timekeeping, such as a clock that must stay correct for days, use a real-time clock module.
// Wrong: may never be true because millis() can skip the exact value.
if (millis() - start == 1000) { }
// Right: true on the first check at or after 1000 ms.
if (millis() - start >= 1000) { }Drift and how to prevent it
In the blink example, previousMillis = now; records when the check ran, not when the interval was supposed to end. If a pass is late by 3 ms, the next interval starts 3 ms late, and the errors add up. Over many blinks the period becomes slightly longer than 500 ms.
For an LED this does not matter. For a task that must keep an exact average rate, advance the timestamp by the interval instead:
const unsigned long PERIOD_MS = 1000;
unsigned long nextTick = 0; // time of the last scheduled tick
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - nextTick >= PERIOD_MS) {
nextTick += PERIOD_MS; // keep the schedule, not the actual time
Serial.println(now);
}
}Here the variable holds the time of the last scheduled tick. A late tick does not shift later ticks. If the sketch stalls for several seconds, for example during a long Serial print or a blocking library call, the code runs once per pass until it catches up. Choose between the two styles deliberately:
| Style | Update | Behavior after a stall | Use for |
|---|---|---|---|
| Reset to now | `previous = now;` | Skips missed intervals and carries on | Blinking, debounce, timeouts |
| Advance by period | `previous += period;` | Fires repeatedly to catch up | Sampling at a fixed average rate |
Measuring how long something takes
millis() also works as a stopwatch. Take a reading before and after, then subtract.
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long start = millis();
delay(123); // stand-in for work you want to measure
unsigned long elapsed = millis() - start;
Serial.print("Took ");
Serial.print(elapsed);
Serial.println(" ms");
delay(1000);
}This reports about 123 ms. For anything under a millisecond, such as timing a single digitalWrite(), use micros(), which counts microseconds. On a 16 MHz AVR board micros() has a resolution of 4 µs, and it wraps after about 71.6 minutes.
A one-shot timeout
Intervals repeat. A timeout fires once. For a timeout, keep a flag that says whether the timer is running, so the action does not repeat.
const unsigned long TIMEOUT_MS = 3000;
unsigned long startTime = 0;
bool waiting = false;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
digitalWrite(LED_BUILTIN, HIGH);
startTime = millis();
waiting = true;
}
void loop() {
if (waiting && millis() - startTime >= TIMEOUT_MS) {
waiting = false; // fire only once
digitalWrite(LED_BUILTIN, LOW); // turn the LED off after 3 seconds
}
}Without the waiting flag, the if stays true on every later pass after the first 3 seconds, and the action repeats continuously. Restarting the timer is a matter of setting startTime = millis(); and waiting = true; again. You will use exactly this shape for debouncing: the timestamp marks the last change, and the elapsed time says whether the signal has been quiet long enough.
Common errors
- Using
delay()anywhere in the loop. Onedelay(100)makes every timer in the sketch late by up to 100 ms and makes button reads miss presses. - Storing the timestamp in a signed or 16-bit variable. See the type table above.
- Comparing with
==instead of>=. - Computing a deadline with
+and comparing with>=, which fails at rollover. - Forgetting to update the timestamp inside the
if. The condition then stays true forever and the action runs on every pass. - Updating the timestamp outside the
if. The elapsed time is then reset on every pass and never reaches the interval. - Calling
millis()inside an interrupt service routine and expecting it to advance. Inside an ISR on AVR, interrupts are disabled, somillis()returns the same value for the whole routine. Read it, but do not wait on it.
What comes next
You now have a non-blocking clock and the subtraction pattern that uses it. The next chapter looks at what happens when the 32-bit counter wraps, and why the subtraction pattern stays correct while other forms do not. After that you apply the pattern to blinking and then to button debouncing.
Exercise
A sketch declares int lastCheck = 0; and runs if (millis() - lastCheck >= 1000) { lastCheck = millis(); ... } on an Uno. The action runs correctly for the first 32 seconds and then behaves strangely. What is wrong, and how do you fix it?
Show answer
On an Uno, int is 16 bits and signed, so lastCheck can hold at most 32,767. When lastCheck = millis(); stores a value above that, it is truncated and wraps to a negative or wrong number. The subtraction then mixes a 32-bit unsigned value with a corrupted timestamp, so the elapsed time is wrong. Declare the variable as unsigned long lastCheck = 0; so it matches the return type of millis().
Exercise
You need an action to fire exactly once, 5 seconds after a button press. Which two variables do you need, and why is a flag necessary?
Show answer
You need an unsigned long timestamp, set to millis() when the press happens, and a bool flag such as waiting, set to true at the same moment. In loop(), check waiting && millis() - startTime >= 5000, then set waiting = false and run the action. Without the flag, the elapsed time stays above 5 seconds after the first match, so the condition remains true and the action repeats on every pass.
Exercise
Why is if (millis() - start == 1000) a poor test, and what should you write instead?
Show answer
The check only runs when loop() reaches it, and millis() can skip values, so the difference may jump from 999 to 1001 or beyond and never equal 1000 exactly. Use >=, as in if (millis() - start >= 1000), which is true on the first check at or after 1000 ms.