Sub topic 11
Blinking without blocking: millis()
This chapter assumes you can already blink an LED with delay(). It also assumes you know pinMode() and digitalWrite(), and that your LED circuit on pin 8 works. You should be comfortable with variables and if statements. You should also know that C++ integer types have fixed sizes and that unsigned types never go negative.
Why delay() gets in the way
delay(500) stops your sketch for 500 milliseconds. The processor sits in a wait loop and runs none of your code during that time. For a single blinking LED this is fine. It becomes a problem as soon as the board has a second job.
Suppose you also want to read a button. With a delay() blink, the button is checked only once per pass through loop(). Each pass takes a full second, because of the two 500 ms pauses. A press shorter than that can fall entirely between two checks and be missed.
const uint8_t LED_PIN = 8;
const uint8_t BUTTON_PIN = 2;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
digitalWrite(LED_PIN, HIGH);
delay(500);
digitalWrite(LED_PIN, LOW);
delay(500);
// Checked only once per second.
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("Button pressed");
}
}Press the button briefly while this runs. The message appears only if your press happens to coincide with the single moment per second when the check runs. The fix is to keep loop() fast and let it decide on each pass whether the LED is due for a change.
What millis() returns
millis() returns the number of milliseconds since the board started running the current program. It returns an unsigned long, which is 32 bits on AVR boards such as the Uno and Nano, and also on most other Arduino cores. A timer inside the microcontroller counts in the background, so reading it costs almost nothing and does not pause your code.
The idea is to treat the clock as a wall clock that you look at, not a timer that you wait on:
- Read the current time.
- Subtract the time of the last toggle.
- If the difference is at least the interval, toggle the LED and remember the new time.
- Otherwise do nothing and return to the top of
loop().
The complete non-blocking blink
This is the pattern from the topic plan. It is the same blink, restructured.
const uint8_t LED_PIN = 8;
const unsigned long INTERVAL_MS = 500;
unsigned long previousToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousToggle >= INTERVAL_MS) {
previousToggle = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
// Other code can run here without waiting for the blink.
}Each piece has a job:
INTERVAL_MSis the time between toggles. Both the on period and the off period last this long, so the full cycle is 1000 ms.previousTogglestores the time of the last toggle. It must live outsideloop(). A local variable would be reset on every pass, and the comparison would never work.ledOnrecords the current state. The sketch toggles it with!and writes the matching level. Keeping the state in a variable means you do not need to read the pin back.nowis read once per pass. Using one snapshot for both the comparison and the update avoids a subtle error wheremillis()changes between two separate calls.
The first toggle happens 500 ms after startup, because previousToggle begins at 0. The LED starts off, since ledOn starts as false and nothing has written the pin yet. Output pins start LOW after pinMode(..., OUTPUT) on most boards.
Adding a second task
Here is the same button check from earlier, now running alongside the blink. Because loop() finishes in microseconds, the button is checked thousands of times per second.
const uint8_t LED_PIN = 8;
const uint8_t BUTTON_PIN = 2;
const unsigned long INTERVAL_MS = 500;
unsigned long previousToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - previousToggle >= INTERVAL_MS) {
previousToggle = now;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
if (digitalRead(BUTTON_PIN) == LOW) {
Serial.println("Button pressed");
}
}Wire the button between pin 2 and GND. INPUT_PULLUP turns on an internal resistor that holds the pin HIGH, so a press reads LOW. While the button is held, the sketch prints the message many times per second. That flood is expected here. Detecting a single press needs edge detection and debouncing, which are separate topics.
Why the subtraction survives rollover
A 32-bit counter holds values up to 4,294,967,295. At one count per millisecond, millis() wraps back to 0 after about 49.7 days. Code that compares absolute times breaks at that moment:
// Fragile: fails when millis() wraps around.
unsigned long nextToggle = 0;
void loop() {
if (millis() >= nextToggle) {
nextToggle = millis() + INTERVAL_MS;
// toggle...
}
}Near the wrap point, millis() + INTERVAL_MS itself overflows to a small number. The check millis() >= nextToggle is then true immediately, and the toggle timing is wrong for one interval. Worse, after the wrap the logic can misbehave in other ways depending on the order of operations.
The subtraction form is safe. Unsigned arithmetic in C++ is defined as modular: results wrap at 2^32. Take previousToggle = 4294967000 and now = 200 after the wrap. The expression now - previousToggle computes 200 - 4294967000 modulo 2^32, which is 496. That is the true elapsed time. The comparison against INTERVAL_MS works across the rollover with no special handling.
This holds only if both operands are unsigned long and the interval you compare against is less than half the counter range, about 24.8 days. Intervals for blinking are far below that.
Choosing the right types
The most common errors in millis() code come from variable types.
| Declaration | Result |
|---|---|
| `unsigned long previousToggle` | Correct. Matches the type `millis()` returns. |
| `int previousToggle` | On AVR boards `int` is 16 bits and signed, so it overflows at 32,767 ms (about 33 seconds). The blink then misbehaves. |
| `unsigned int previousToggle` | Wraps at 65,535 ms (about 65 seconds). The blink fails around that point. |
| `long previousToggle` | Wide enough, but signed. Subtraction still often works, but comparisons can produce surprising results. Avoid it. |
| `const int INTERVAL_MS = 500` | Works for small values, but mixing signed and unsigned types invites subtle bugs. Use `unsigned long`. |
A symptom worth remembering is a sketch that blinks correctly for roughly 30 or 65 seconds and then stops or speeds up. That is a type-size problem, not a wiring problem.
Drift and catching up
The sketch above sets previousToggle = now. If loop() reaches the check late, for example 3 ms after the interval elapsed, those 3 ms are lost. Over many toggles the blink runs slightly slower than ideal. For an LED nobody notices.
When you need a steady average rate, advance the stored time by the interval instead:
const uint8_t LED_PIN = 8;
const unsigned long INTERVAL_MS = 500;
unsigned long previousToggle = 0;
bool ledOn = false;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousToggle >= INTERVAL_MS) {
previousToggle += INTERVAL_MS;
ledOn = !ledOn;
digitalWrite(LED_PIN, ledOn ? HIGH : LOW);
}
}Now each scheduled toggle lands on a fixed grid: 500, 1000, 1500 ms and so on, regardless of small delays. The trade-off appears when something stalls the loop. If a long operation takes 2 seconds, the difference is 2000 ms, so the condition stays true for several passes in a row. The LED toggles once per pass until previousToggle catches up, producing a rapid burst of flashes. With previousToggle = now, the sketch would instead skip the missed toggles and carry on.
| Update style | Behavior | Best for |
|---|---|---|
| `previousToggle = now` | Each interval counts from when the toggle actually happened. Tolerates stalls. Drifts slightly. | Indicator LEDs, simple tasks |
| `previousToggle += INTERVAL_MS` | Fixed schedule with no cumulative drift. Bursts after a stall. | Sampling at a steady rate, clocks |
Independent timers for several LEDs
Each periodic task gets its own interval and its own previous variable. Two LEDs at different rates need no coordination.
const uint8_t FAST_LED_PIN = 8;
const uint8_t SLOW_LED_PIN = 9;
const unsigned long FAST_INTERVAL_MS = 200;
const unsigned long SLOW_INTERVAL_MS = 1000;
unsigned long previousFast = 0;
unsigned long previousSlow = 0;
bool fastOn = false;
bool slowOn = false;
void setup() {
pinMode(FAST_LED_PIN, OUTPUT);
pinMode(SLOW_LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousFast >= FAST_INTERVAL_MS) {
previousFast = now;
fastOn = !fastOn;
digitalWrite(FAST_LED_PIN, fastOn ? HIGH : LOW);
}
if (now - previousSlow >= SLOW_INTERVAL_MS) {
previousSlow = now;
slowOn = !slowOn;
digitalWrite(SLOW_LED_PIN, slowOn ? HIGH : LOW);
}
}Doing this with delay() is not practical, because one pause would hold up the other LED. Wire the second LED to pin 9 with its own series resistor, exactly like the first.
Limits of the technique
This approach is cooperative. Every task must return to loop() quickly, and nothing forces a slow task to yield. Keep these limits in mind:
- Any
delay()anywhere reintroduces blocking. A singledelay(100)in another function adds 100 ms of latency to every timer in the sketch. - Slow calls stall the loop. Long serial prints,
pulseIn()with a large timeout, and some sensor libraries can take many milliseconds. Your blink then becomes uneven. - Resolution is limited. On a 16 MHz AVR,
millis()advances in steps of 1 ms and is read as a snapshot. You cannot toggle faster than the loop runs, and jitter of a few milliseconds is normal. For precise timing use hardware timers ormicros(). - Interrupts delay the counter on some boards. Code that disables interrupts for a long time can make
millis()lose counts. Ordinary sketches do not hit this. - It does not replace an RTOS. For many tasks with strict deadlines, a scheduler library or real-time operating system is a better fit than a growing pile of
previousvariables.
When a sketch grows to four or five timed tasks, consider a state machine or a small scheduler. The millis() check remains the building block underneath either.
Troubleshooting a non-blocking blink
| Symptom | Likely cause |
|---|---|
| LED never toggles | `previousToggle` declared inside `loop()`, so it resets every pass. Or the interval is larger than expected. |
| LED stays on and does not blink | `ledOn` is toggled but `digitalWrite()` is missing, or it writes a constant instead of `ledOn`. |
| Toggles on every pass (looks dim and steady) | `previousToggle` is never updated inside the `if` block. |
| Works for about 30 seconds, then misbehaves | `int` used for time variables. Change to `unsigned long`. |
| Blink is irregular | Another part of the sketch uses `delay()` or a slow blocking call. |
| LED toggles once, then waits much longer | Mixed up `INTERVAL_MS` units (seconds versus milliseconds). |
If the wiring is in question, go back to the checklist chapter. The external LED circuit is identical for both timing styles.
Exercise
A student writes int lastToggle = 0; and compares millis() - lastToggle >= 1000 to blink an LED on an Uno. The LED blinks correctly at first and then behaves oddly after roughly half a minute. Explain why, and give the fix.
Show answer
On an Uno, int is a signed 16-bit type with a maximum of 32,767. Once millis() exceeds 32,767 ms (about 33 seconds), the stored lastToggle value no longer fits, so it overflows to a negative number, and the subtraction and comparison give wrong results. The fix is to declare unsigned long lastToggle = 0; so it matches the return type of millis().
Exercise
Modify the two-LED sketch so the LED on pin 8 is on for 100 ms and off for 900 ms, while still using only millis(). What changes are needed?
Show answer
Use two intervals and pick the one that matches the current state. Declare const unsigned long ON_MS = 100; and const unsigned long OFF_MS = 900;. In loop(), compute unsigned long interval = ledOn ? ON_MS : OFF_MS; and test now - previousToggle >= interval. The body that updates previousToggle, flips ledOn and writes the pin stays the same.
Exercise
A sketch uses previousToggle += INTERVAL_MS and then a 3-second delay(3000) is added in loop() for a sensor read. With INTERVAL_MS = 500, what does the LED do after the delay ends, and why?
Show answer
After the delay, now - previousToggle is about 3000, which is far above 500. On each following pass the condition is true, and previousToggle increases by only 500, so the LED toggles about six times in rapid succession until previousToggle catches up with the clock. With previousToggle = now the sketch would toggle only once and resume normal timing. Removing the delay() is the better fix.