Sub topic 9
Printing at a steady rate without delay
This chapter assumes you can write a sketch with setup() and loop(), call Serial.begin() and Serial.println(), and read a pin with analogRead(). You should also know that unsigned long is a 32-bit type that cannot hold negative values.
Why delay() gets in the way
Most first serial sketches end loop() with delay(1000). That slows the output to a readable pace, but delay() halts your sketch. For that whole second the board cannot read a button, check Serial.available(), or update an LED.
The cost shows up as soon as the sketch does more than one thing. Suppose you print a sensor value every 500 ms and also want to react to a button. With delay(500), a button press shorter than 500 ms can be missed completely. Serial input from the Serial Monitor is less affected, because the receive buffer holds incoming bytes. The reply to your command is still late, though.
The fix is to let loop() run thousands of times per second and print only when enough time has passed.
The millis() pattern
millis() returns the number of milliseconds since the board started running the sketch. It returns an unsigned long. The pattern has three steps:
- Remember when you last printed.
- On every pass through
loop(), read the current time. - If the difference is at least your interval, print and update the remembered time.
unsigned long lastPrint = 0;
const unsigned long PRINT_INTERVAL = 500;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - lastPrint >= PRINT_INTERVAL) {
lastPrint = now;
Serial.println(analogRead(A0));
}
// other work can run here without being blocked by delay()
}The if test is false most of the time, so loop() returns almost immediately. Any code placed after the if runs on every pass, not once per interval.
Why subtraction and not comparison
You may be tempted to write if (millis() > lastPrint + PRINT_INTERVAL). This works for a while and then fails.
millis() is a 32-bit counter. It reaches 4,294,967,295 after about 49.7 days and then wraps back to 0. Near that point, lastPrint + PRINT_INTERVAL can overflow to a small number, and the comparison fires on every pass or at the wrong moment.
The subtraction form now - lastPrint is safe. Unsigned arithmetic wraps around in the same way the counter does, so the difference is still correct across the rollover. For example, if lastPrint is 4,294,967,000 and now is 200 after the wrap, now - lastPrint evaluates to 496. That is the real elapsed time.
This only works if all three values are unsigned long. If you store the time in an int, it overflows after 32 seconds on an Uno, where int is 16 bits. Even a long (signed) breaks the guarantee on comparisons.
Drift: lastPrint = now versus lastPrint += interval
There are two ways to update the remembered time, and they behave differently.
lastPrint = now;restarts the timer from the moment you noticed it had expired. Ifloop()was busy and you noticed 7 ms late, the next interval starts 7 ms late. Over many cycles, the period becomes slightly longer than the interval. This is called drift.lastPrint += PRINT_INTERVAL;advances the schedule by exactly one interval. Lateness does not accumulate, so the average rate stays exact.
unsigned long nextPrint = 0;
const unsigned long PRINT_INTERVAL = 1000;
void setup() {
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - nextPrint >= PRINT_INTERVAL) {
nextPrint += PRINT_INTERVAL;
Serial.print(F("tick at "));
Serial.println(now);
}
}Here nextPrint is the time the last tick was scheduled for, so the check is still an elapsed-time subtraction. The printed now values will be 1000, 1001, 2000, and so on, jittering by a millisecond or so, but the average spacing stays at 1000 ms.
The += form has one trap. If the sketch stalls for several intervals, for example during a long blocking call, the condition stays true on following passes and the sketch prints several times in quick succession to catch up. If you prefer to skip missed ticks, use lastPrint = now. For a human-readable log, either form is fine. For a data logger where the sample count matters, prefer +=.
| Update style | Period over time | Behavior after a long stall |
|---|---|---|
| `last = now` | Drifts slightly longer | Prints once, then resumes normal spacing |
| `last += interval` | Stays exact on average | Prints repeatedly until caught up |
Several timers in one sketch
Each periodic job gets its own variable pair. The example below prints a sensor value every 500 ms, prints a heartbeat message every 5 seconds, and handles a one-character command on every pass.
const int LED_PIN = 13;
unsigned long lastSensor = 0;
unsigned long lastHeartbeat = 0;
const unsigned long SENSOR_INTERVAL = 500;
const unsigned long HEARTBEAT_INTERVAL = 5000;
void setup() {
Serial.begin(9600);
pinMode(LED_PIN, OUTPUT);
Serial.println(F("Send 1 or 0 to switch the LED"));
}
void loop() {
unsigned long now = millis();
if (now - lastSensor >= SENSOR_INTERVAL) {
lastSensor = now;
Serial.print(F("A0="));
Serial.println(analogRead(A0));
}
if (now - lastHeartbeat >= HEARTBEAT_INTERVAL) {
lastHeartbeat = now;
Serial.print(F("alive, uptime ms: "));
Serial.println(now);
}
if (Serial.available() > 0) {
char c = Serial.read();
if (c == '1') digitalWrite(LED_PIN, HIGH);
if (c == '0') digitalWrite(LED_PIN, LOW);
}
}Type 1 into the Serial Monitor while the readings scroll. The LED responds within one pass of loop(), which is far under a millisecond for this code. With delay(500) in the loop, the response could lag by half a second.
Reading millis() once into now at the top of loop() is deliberate. All the checks in that pass then compare against the same instant, which keeps the timers consistent with each other.
How steady is "steady"?
The millis() timer is accurate to the board's clock, not to the millisecond on every print. Keep these limits in mind:
- Timing resolution. On a 16 MHz Uno,
millis()advances in steps of about 1 ms, so intervals under a few milliseconds are coarse. Usemicros()for finer timing. - Check frequency. Your print can only happen when
loop()reaches theif. If another part ofloop()takes 30 ms, a 10 ms timer cannot fire more often than every 30 ms. - Clock accuracy. Boards that use a ceramic resonator, such as many Unos, can be off by about 0.5 percent. That is roughly 7 minutes of error per day, which is fine for debugging output and not for a clock.
- Print cost. Sending a line is not free. At 9600 baud, each character takes about 1 ms to transmit, so a 20-character line occupies the serial port for about 20 ms. Printing every 10 ms at that speed cannot keep up. Raise the baud rate or print less, as the later chapter on serial buffers explains.
Common mistakes
- Forgetting to update the timestamp. If you omit
lastPrint = now;, the condition stays true after the first interval and the sketch prints on every pass. - Declaring the timestamp inside loop(). A local
unsigned long lastPrint = 0;is reset on every pass, so the condition is true or false in a fixed way and never tracks time. Declare it globally or asstatic. - Mixing
delay()back in. Onedelay(100)elsewhere inloop()caps the whole sketch at 10 passes per second. Search the sketch for it when your timer seems late. - Comparing with
==.if (now - lastPrint == 500)fires only if you happen to sample at that exact millisecond. Use>=. - Using a signed type. As described above,
intandlongtimestamps break after short or long run times.
A static local variable keeps the timer variable close to the code that uses it, and it still survives between calls:
void loop() {
static unsigned long lastPrint = 0;
unsigned long now = millis();
if (now - lastPrint >= 250) {
lastPrint = now;
Serial.println(analogRead(A0));
}
}Exercise
A sketch should print a reading every 2 seconds and also blink an LED that toggles every 300 ms, without delay(). It prints correctly for a while, but after about 32 seconds it stops printing. The timer variable is declared as int lastPrint = 0;. What is the cause, and what is the fix? Also, why is the check written as now - lastPrint >= 2000 and not now >= lastPrint + 2000?
Show answer
On an Uno, int is 16 bits, so it holds at most 32,767. A millis() value stored in it overflows after about 32.8 seconds, and the subtraction no longer produces the true elapsed time. Declare lastPrint (and now) as unsigned long. The subtraction form is used because unsigned subtraction stays correct when millis() wraps from its maximum back to 0 after about 49.7 days, while lastPrint + 2000 can overflow and make the comparison wrong. The LED needs its own pair of variables, for example lastBlink and a 300 ms interval, checked in the same loop() pass.