Sub topic 7
Blinking without delay()
This chapter assumes you can write a basic sketch with setup() and loop(), use pinMode() and digitalWrite(), and read C++ if statements, bool variables and integer types. It also assumes you have seen that delay() pauses the whole sketch and that millis() returns the milliseconds since the board started. Here you turn that clock into a reusable pattern: do something every N milliseconds while loop() keeps running.
The idea: ask "is it time yet?"
delay(500) says "do nothing for 500 ms." The non-blocking version asks a different question on every pass through loop(): "have 500 ms passed since I last toggled the LED?" If the answer is no, the sketch moves on. If yes, it toggles the LED and records the time.
This needs only two things:
- A constant that holds the interval.
- A variable that remembers when the action last happened.
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 a typical board loop() runs thousands of times per second. Almost every pass finds that fewer than 500 ms have elapsed, skips the if body and returns immediately. Roughly twice per second the condition is true and the LED changes.
Walking through the code
Reading the clock once. The sketch copies millis() into now and uses now for both the comparison and the stored timestamp. millis() keeps counting while the pass runs. If you called it twice, the comparison and the saved value could differ by a millisecond or more.
The elapsed-time test. now - previousMillis is the time since the last toggle. Both variables are unsigned long, so the subtraction is correct even when millis() wraps back to 0 after about 49.7 days. The previous chapter covered why. Keep the subtraction form, now - previous >= interval, and do not rewrite it as now >= previous + interval.
Saving the timestamp. Setting previousMillis = now starts the next interval from this moment. Forgetting this line makes the condition stay true forever, and the LED then toggles on every pass, which looks like a dim, constantly lit LED.
Toggling the state. The sketch stores the LED state in ledState and writes it out. This is clearer than reading the pin back, and it works the same way for any output. !ledState flips LOW to HIGH and back, because LOW is 0 and HIGH is 1.
Choosing the right variable types
| Item | Type | Why |
|---|---|---|
| Interval | `const unsigned long` | Same type as the clock, so the comparison involves no signed/unsigned conversion. |
| Previous timestamp | `unsigned long` | `millis()` returns `unsigned long`, which is 32 bits on AVR boards such as the Uno. |
| Pin number | `const uint8_t` | Pins fit in one byte. |
| LED state | `bool` | It has two values. |
The most common typing mistake is storing a timestamp in an int. On an Uno, int is 16 bits and tops out at 32767. The value wraps after about 32 seconds, and the timing breaks in a way that looks random. The Uno's unsigned int is 16 bits too, and it wraps at about 65 seconds.
Drift: `= now` versus `+= interval`
The sketch above sets previousMillis = now. That is simple and usually right, but it has a subtle effect. The check only runs when loop() gets to it. If the pass is late by 3 ms, now is 503 ms past the previous timestamp, and the extra 3 ms is thrown away. Each cycle can pick up a little lateness, so over minutes the blink period becomes slightly longer than 500 ms.
If you need a fixed schedule, add the interval instead:
const unsigned long INTERVAL_MS = 500;
unsigned long nextToggle = 0;
bool ledState = LOW;
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
nextToggle = millis();
}
void loop() {
unsigned long now = millis();
if (now - nextToggle >= INTERVAL_MS) {
nextToggle += INTERVAL_MS;
ledState = !ledState;
digitalWrite(LED_BUILTIN, ledState);
}
}Here nextToggle is really "the time of the last scheduled toggle", so the variable name should say that. A lateness of 3 ms no longer accumulates. The next toggle is still due at the original grid point, so it happens 497 ms later.
Trade-offs between the two forms:
previousMillis = nowkeeps a minimum gap of one interval between actions. It is the safer choice for things like debounce windows and timeouts, where "at least N ms since the last event" is what you mean.previousMillis += INTERVAL_MSkeeps the long-run rate exact. Use it for sampling and for periodic output where the average rate matters.- With
+=, a long stall inloop()leaves the code "behind". If something blocks for 2 seconds, the condition stays true for several passes and the action fires in a quick burst until the schedule catches up. If bursts are a problem, reset withpreviousMillis = nowwhenever you detect that you are more than one interval behind.
Granularity and jitter
millis() has a resolution of about 1 ms on 16 MHz AVR boards. Its counter is driven by a hardware timer that actually ticks every 1.024 ms, and the library skips a count now and then to compensate. That means two reads of millis() can differ by 2 ms occasionally. For blinking, this does not matter. For tasks under about 5 ms, micros() or a hardware timer is a better fit.
The actual action time also depends on how long one pass of loop() takes. If the other work in loop() takes 20 ms per pass, your 500 ms blink will fire between 500 and 520 ms late. So the rule for this pattern is that every piece of work in loop() must be short. A non-blocking pattern works only if nothing else blocks. A stray delay(100), a slow Serial.print() of a long string at a low baud rate, or a long for loop all stretch every task.
Running two intervals
The pattern scales by giving each task its own constant and its own timestamp:
const uint8_t LED_A = 8;
const uint8_t LED_B = 9;
const unsigned long INTERVAL_A_MS = 300;
const unsigned long INTERVAL_B_MS = 700;
unsigned long previousA = 0;
unsigned long previousB = 0;
bool stateA = LOW;
bool stateB = LOW;
void setup() {
pinMode(LED_A, OUTPUT);
pinMode(LED_B, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - previousA >= INTERVAL_A_MS) {
previousA = now;
stateA = !stateA;
digitalWrite(LED_A, stateA);
}
if (now - previousB >= INTERVAL_B_MS) {
previousB = now;
stateB = !stateB;
digitalWrite(LED_B, stateB);
}
}The two blocks do not know about each other. With delay() you would have to compute a combined schedule by hand. Here the LEDs go in and out of step on their own, and you can add a third task without touching the first two. The next chapters reuse exactly this structure for a debounced button.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| LED glows steadily at half brightness | `previousMillis` is never updated, so the toggle happens on every pass | Add `previousMillis = now;` inside the `if` |
| Timing goes wrong after about 32 seconds | Timestamp stored in `int` | Use `unsigned long` |
| Blink works for weeks, then one early or stuck event | Comparison written as `now >= previous + interval` | Use `now - previous >= interval` |
| Blink is irregular when other code is added | Other code in `loop()` blocks or runs for tens of milliseconds | Remove `delay()` calls and shorten each pass |
| Two tasks fire together and share timing oddly | Both tasks share one timestamp variable | Give each task its own timestamp |
| First blink arrives late | `previousMillis` starts at 0 and the first interval counts from boot | Acceptable, or set the timestamp in `setup()` if the start moment matters |
Exercises
Exercise
In the blink sketch, the if body sets previousMillis = now;. What would you see if that line were deleted, and why?
Show answer
The condition now - previousMillis >= INTERVAL_MS would become true after the first 500 ms and stay true, because previousMillis would never move forward. The LED would toggle on every pass of loop(), thousands of times per second, so it would look constantly lit at reduced brightness instead of blinking.
Exercise
A sketch should sample a sensor exactly 100 times per second on average, even if some passes of loop() are a few milliseconds late. Should it use previousMillis = now or previousMillis += 10? Explain, and name one risk of your choice.
Show answer
Use previousMillis += 10. It keeps the schedule anchored to fixed points, so lateness in one pass is made up in the next and the average rate stays at 100 samples per second. With = now each late pass would push all later samples back. The risk of += is that after a long stall the code is several intervals behind and fires a burst of catch-up samples. You can guard against this by resetting previousMillis = now when the code is more than one interval behind.
Exercise
Add a third task to the two-LED sketch: the built-in LED should blink every 1000 ms. Which new variables and which new block do you need?
Show answer
Add const unsigned long INTERVAL_C_MS = 1000;, unsigned long previousC = 0; and bool stateC = LOW;, and call pinMode(LED_BUILTIN, OUTPUT); in setup(). In loop(), add a block if (now - previousC >= INTERVAL_C_MS) { previousC = now; stateC = !stateC; digitalWrite(LED_BUILTIN, stateC); }. The existing two blocks stay unchanged.