Sub topic 13
Timing without delay() using millis()
This chapter assumes you can write a sketch with setup() and loop(), use digitalWrite(), declare variables of types like byte and unsigned long, write if conditions, and define a function with parameters and a return value. You also need the Serial Monitor for the last example.
Why delay() gets in the way
delay(500) stops your sketch for 500 milliseconds. The board does nothing else during that time. It does not read buttons, update other outputs, or check the serial port. A button press shorter than the delay can be missed completely.
This is fine for a single blinking LED. It breaks down when a sketch must do two or more things on different schedules, such as blinking a status LED while watching a button.
The fix is to stop waiting and start checking. On every pass through loop(), ask whether enough time has passed since the last action. If it has, act. If not, move on. Because loop() never stalls, it runs thousands of times per second and everything stays responsive.
What millis() returns
millis() returns the number of milliseconds since the board started running the current sketch. Three facts matter:
- The return type is
unsigned long, a 32-bit unsigned integer on AVR boards such as the Uno. - The counter starts at 0 on power-up or reset.
- It runs in the background, driven by a hardware timer. Your code does not need to do anything to keep it counting.
Store its result in an unsigned long variable. Any smaller type loses part of the value.
The core pattern
You keep one variable for the time of the last action and compare it to the current time.
const byte ledPin = LED_BUILTIN;
const unsigned long interval = 500;
unsigned long previousMillis = 0;
bool ledOn = false;
void setup() {
pinMode(ledPin, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousMillis >= interval) {
previousMillis = now;
ledOn = !ledOn;
digitalWrite(ledPin, ledOn ? HIGH : LOW);
}
// Other work can run here on every pass through loop().
}The steps in each pass of loop() are:
- Read the clock once into
now. - Compute the elapsed time,
now - previousMillis. - If the elapsed time has reached the interval, record the new timestamp and perform the action.
- Fall through and let any other code run.
Why subtraction, not addition
You may be tempted to write if (now >= previousMillis + interval). Avoid it. The subtraction form keeps working when the counter wraps around, and the addition form does not.
Rollover and why the subtraction survives it
An unsigned long on the Uno holds values up to 4,294,967,295. After about 49.7 days of continuous running, millis() wraps back to 0. This is called rollover.
Unsigned arithmetic is modular. Subtracting a large number from a small one wraps around the same way the counter does, so the difference is still the true elapsed time. Suppose previousMillis was recorded 296 ms before the rollover and now is 200 ms after it.
| Quantity | Value |
|---|---|
| previousMillis | 4,294,967,000 |
| now (after wrap) | 200 |
| now - previousMillis (unsigned) | 496 |
| Real elapsed time | 296 + 200 = 496 ms |
The result is correct as long as both variables are unsigned long and the interval you measure is shorter than the full range. With the addition form, previousMillis + interval can itself overflow to a small number. The condition then becomes true at the wrong moment.
Wrapping the test in a function
The comparison is the same every time, so it suits a small function. This uses parameters and a return value, as in the earlier chapter on functions.
bool hasElapsed(unsigned long now, unsigned long start, unsigned long interval) {
return now - start >= interval;
}The function does not modify the stored timestamp, so the caller stays in control of when to reset it. That keeps the function free of hidden state.
Running several tasks on different schedules
Each task gets its own interval and its own timestamp. The sketch below blinks the built-in LED every 500 ms, prints the uptime every 2 seconds, and copies a button's state to a second LED on every pass, with no delay. Wire a button between pin 2 and GND, and an LED with a resistor on pin 8.
const byte blinkPin = LED_BUILTIN;
const byte buttonPin = 2;
const byte mirrorPin = 8;
const unsigned long blinkInterval = 500;
const unsigned long reportInterval = 2000;
unsigned long lastBlink = 0;
unsigned long lastReport = 0;
bool blinkOn = false;
bool hasElapsed(unsigned long now, unsigned long start, unsigned long interval) {
return now - start >= interval;
}
void setup() {
pinMode(blinkPin, OUTPUT);
pinMode(mirrorPin, OUTPUT);
pinMode(buttonPin, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (hasElapsed(now, lastBlink, blinkInterval)) {
lastBlink += blinkInterval;
blinkOn = !blinkOn;
digitalWrite(blinkPin, blinkOn ? HIGH : LOW);
}
if (hasElapsed(now, lastReport, reportInterval)) {
lastReport += reportInterval;
Serial.print("Uptime (s): ");
Serial.println(now / 1000);
}
// Runs on every pass. With INPUT_PULLUP, a pressed button reads LOW.
digitalWrite(mirrorPin, digitalRead(buttonPin) == LOW ? HIGH : LOW);
}Hold the button down at any moment, including while the blink LED is mid-cycle. The second LED lights immediately. With delay(500) it could lag by up to half a second.
Resetting with = now versus += interval
The two sketches above use different reset styles, and they behave differently.
previousMillis = nowrestarts the interval from the moment the check ran. If a pass is delayed by a few milliseconds, that lateness is added to every cycle, so the schedule slowly drifts.previousMillis += intervaladvances the timestamp by exactly one interval. The schedule stays locked to the original rhythm with no cumulative drift.
The trade-off appears when the sketch stalls for a long time, for example during a slow operation. With +=, the check stays true on consecutive passes until the timestamp catches up, so the action fires several times in quick succession. With = now, it fires once and the missed cycles are dropped. Choose += when the long-run rate matters, such as sampling at a fixed frequency. Choose = now when you only need a minimum gap between actions.
Common errors
- Using
intorlongfor timestamps. Useunsigned long. A signed type gives wrong results at rollover, andinton AVR overflows within 33 seconds. - Writing
now >= previous + interval. This fails near rollover. Always subtract. - Leaving a
delay()somewhere in the loop. Onedelay(1000)in another function undoes the benefit, because every task waits for it. Search the whole sketch, including library calls that block. - Forgetting to update the timestamp. If you never reassign
previousMillis, the condition stays true after the first interval and the action runs on every pass. - Calling
millis()repeatedly in one pass. Each call can return a different value. Read it once intonowand use that value for every check in the pass. - Doing slow work inside the timed block. If the block takes longer than the interval, the schedule falls behind no matter which reset style you use.
Limits to know about
millis() is a software-visible clock with limits.
- Accuracy. Boards with a ceramic resonator, like many Uno clones, can be off by about 0.5 percent. That is roughly 7 minutes per day. Boards with a crystal are tighter. For calendar-grade time, use a real-time clock module.
- Resolution. On a 16 MHz AVR, the value advances in steps of 1 ms, and not every value is hit on every pass. Do not test for equality such as
now == target. Use>=on an elapsed difference. - Interrupts. Long stretches with interrupts disabled can cause
millis()to miss ticks. - Not a scheduler. It does not interrupt your code. A task runs only when
loop()reaches it, so every other part of the sketch must return quickly. For finer timing,micros()works the same way with microseconds and wraps after about 71.6 minutes.
Exercises
Exercise
A sketch declares int previousMillis = 0; and const int interval = 1000; and uses if (millis() - previousMillis >= interval). It works at first, then behaves strangely after about half a minute on an Uno. Why, and what is the fix?
Show answer
On an Uno, int is 16 bits and holds at most 32,767, which is reached after about 32.8 seconds of millis(). The value stored in previousMillis then overflows, and the comparison no longer reflects the real elapsed time. Declare previousMillis as unsigned long (and preferably interval as const unsigned long).
Exercise
Extend the multi-task sketch with a third task: every 3000 ms, print "Button is pressed" or "Button is released" based on the current state of pin 2. Which new variables and which block do you add, and does the new task need any delay()?
Show answer
Add const unsigned long buttonReportInterval = 3000; and unsigned long lastButtonReport = 0;. In loop(), add if (hasElapsed(now, lastButtonReport, buttonReportInterval)) { lastButtonReport += buttonReportInterval; Serial.println(digitalRead(buttonPin) == LOW ? "Button is pressed" : "Button is released"); }. No delay() is needed. The task is just another timestamp check inside loop().