Sub topic 9
Fading Without Blocking: Using millis() Instead of delay()
What this chapter assumes
You should already be comfortable with the following:
- Writing a sketch with
setup()andloop(). - Using
pinMode(),digitalWrite(), andanalogWrite(). - The stepped fade from the previous chapter, where
brightnesschanges by a fixedstepand reverses at 0 and 255.
You do not need to know anything about timers or interrupts. This chapter explains the parts of them that matter here.
Why delay() gets in the way
The stepped fade ends each pass of loop() with delay(20). That call stops the processor from running your code for 20 ms. During that time the sketch cannot read a button, poll a sensor, or update a second LED. It can only wait.
With one LED this is fine. With two jobs it becomes a problem. Suppose you want the LED to fade and you also want a button to pause the fade. If a button press falls inside a 20 ms delay(), you may miss it. If you add a 500 ms delay() somewhere else, the fade stutters because its steps now occur 500 ms apart.
The fix is to stop asking "wait 20 ms, then continue". Instead, loop() runs as fast as it can and asks on every pass: "Has 20 ms passed since the last step? If not, move on."
How millis() works
millis() returns the number of milliseconds since the board started running the current sketch. Its return type is unsigned long, a 32-bit unsigned integer on the Uno.
- It starts at 0 at power-up or reset.
- It increases in the background. On an Uno, Timer0 triggers an interrupt about every 1.024 ms, and the Arduino core adds a correction so the count stays accurate over time. You can read it at any moment without it blocking anything.
- After 2^32 milliseconds (about 49.7 days) it wraps from 4294967295 back to 0. This is called rollover.
Reading millis() takes a few microseconds. It is safe to call on every pass of loop().
The non-blocking pattern
The pattern has three parts. You store a timestamp, read the clock, and compare the elapsed time to an interval.
const uint8_t LED_PIN = 9;
const unsigned long INTERVAL_MS = 20;
unsigned long lastStepTime = 0;
int brightness = 0;
int step = 5;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
unsigned long now = millis();
if (now - lastStepTime >= INTERVAL_MS) {
lastStepTime = now;
analogWrite(LED_PIN, brightness);
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
}
// Other work can run here on every pass through loop()
}The fade logic is the same as before. Only the trigger has changed. Here is what each piece does:
nowis read once per pass and reused. If you calledmillis()several times in one pass, the values could differ slightly, and your comparisons would not all describe the same instant.lastStepTimeremembers when the last step happened. It lives outsideloop()so it keeps its value between passes.now - lastStepTime >= INTERVAL_MSis the elapsed-time test. When it is true, the code runs one fade step and stores the new timestamp.- Everything after the
ifblock runs on every pass, so other tasks get constant attention.
On most passes the answer is "no", and the loop takes only a few microseconds. That is the point: the sketch spends almost all its time free for other work.
Why subtraction survives rollover
Beginners often write the test as if (millis() >= lastStepTime + INTERVAL_MS). This works for 49 days and then fails. When millis() wraps to a small number, the sum lastStepTime + INTERVAL_MS can still be huge, so the condition stays false for a very long time.
The subtraction form now - lastStepTime does not have this problem. Unsigned arithmetic wraps modulo 2^32, so the difference stays correct across the rollover. For example, suppose lastStepTime is 4294967290, which is 6 ms before the wrap. Suppose now is 10, which is 10 ms after the wrap. Then 10 - 4294967290 wraps around to 16, which is the true elapsed time.
This works only if both values are unsigned long. If you store the timestamp in an int or a long, you lose the guarantee. An int on the Uno is 16 bits and overflows after about 32 seconds.
Choosing how to update the timestamp
There are two common ways to record the time of a step, and they behave differently when the loop runs late.
| Update rule | Behavior | Use it when |
|---|---|---|
| `lastStepTime = now;` | Each step starts at least one interval after the previous step actually ran. Lateness accumulates, so the average rate is slightly slower than planned. | Smooth visual effects, where exact long-term timing does not matter. |
| `lastStepTime += INTERVAL_MS;` | Steps stay locked to a fixed schedule. If one step is late, the next comes sooner to catch up. | Sampling or counting, where the average rate must be exact. |
The += rule has a catch. If something blocks the loop for much longer than the interval, such as a slow Serial.print() or a long calculation, the sketch will run several steps back to back to catch up. For a fade, that looks like a sudden jump. If you use +=, guard against it. One option is to reset lastStepTime = now when the lag exceeds a few intervals.
For fading an LED, lastStepTime = now is the simpler and safer choice.
Running several tasks
The benefit shows when you give loop() more than one job. This sketch fades the LED on pin 9, blinks the built-in LED every 500 ms, and uses a button on pin 2 to pause and resume the fade. Each task has its own timestamp and its own function.
const uint8_t LED_PIN = 9;
const uint8_t BUTTON_PIN = 2;
const uint8_t STATUS_PIN = LED_BUILTIN;
const unsigned long FADE_INTERVAL_MS = 20;
const unsigned long BLINK_INTERVAL_MS = 500;
const unsigned long DEBOUNCE_MS = 30;
unsigned long lastFadeTime = 0;
unsigned long lastBlinkTime = 0;
unsigned long lastChangeTime = 0;
int brightness = 0;
int step = 5;
bool statusOn = false;
bool fadeEnabled = true;
bool lastReading = HIGH;
bool stableState = HIGH;
void updateFade(unsigned long now) {
if (!fadeEnabled) return;
if (now - lastFadeTime < FADE_INTERVAL_MS) return;
lastFadeTime = now;
analogWrite(LED_PIN, brightness);
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
}
void updateBlink(unsigned long now) {
if (now - lastBlinkTime < BLINK_INTERVAL_MS) return;
lastBlinkTime = now;
statusOn = !statusOn;
digitalWrite(STATUS_PIN, statusOn ? HIGH : LOW);
}
void updateButton(unsigned long now) {
bool reading = digitalRead(BUTTON_PIN);
if (reading != lastReading) {
lastReading = reading;
lastChangeTime = now;
}
if (now - lastChangeTime >= DEBOUNCE_MS && reading != stableState) {
stableState = reading;
if (stableState == LOW) { // pressed (INPUT_PULLUP, so LOW = pressed)
fadeEnabled = !fadeEnabled;
}
}
}
void setup() {
pinMode(LED_PIN, OUTPUT);
pinMode(STATUS_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP);
}
void loop() {
unsigned long now = millis();
updateFade(now);
updateBlink(now);
updateButton(now);
}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.
Each update...() function starts with an early return when it is not yet time. This keeps the logic flat and easy to read. The button handler also uses millis() for its debounce: it accepts a new state only after the reading has been steady for 30 ms. No delay() is needed there either.
When the fade is paused, the LED holds its last brightness. The analogWrite() setting persists because the hardware timer keeps generating the PWM signal without help from your code.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Fade is much slower than expected | A `delay()` or slow `Serial.print()` call remains in `loop()`. | Remove blocking calls, or lower the print rate by giving it its own timer. |
| Fade works for weeks, then freezes | Timestamp stored in the wrong type, or the test is written as `millis() >= last + interval`. | Use `unsigned long` and `now - last >= interval`. |
| All tasks fire at the same instant every time | All timestamps started at 0 with intervals that share a common multiple. | This is usually harmless. If it causes a load spike, offset the starting timestamps. |
| Fade steps look jerky after adding a task | One task spends several milliseconds in a single pass. | Shorten that task, or split its work across several passes. |
| Variables reset on every pass | Timestamp declared inside `loop()` without `static`. | Declare it globally, or use `static unsigned long last = 0;`. |
Limits of the technique
- Resolution is about 1 ms. You cannot reliably schedule things faster than that. For microsecond timing,
micros()has a 4 µs resolution on a 16 MHz Uno, and it rolls over after about 71 minutes. - It is cooperative. Nothing interrupts a task that runs long. If any function in
loop()takes 50 ms, every other task waits 50 ms. The fade will still look smooth if its interval is 20 ms and its steps are small, but a 50 ms pause per pass would be visible. millis()shares Timer0 with pins 5 and 6. On an Uno,millis()depends on Timer0. Pins 5 and 6 also use Timer0 for PWM. Changing the Timer0 prescaler to alter PWM frequency on those pins makesmillis()anddelay()run at the wrong speed. Pin 9, used in these examples, belongs to Timer1, so it is safe to reconfigure.- It does not run while interrupts are disabled. If you call
noInterrupts()for long, the clock misses ticks andmillis()falls behind.
Checking your work
Test the non-blocking claim directly. Add a task that prints to Serial every 1000 ms and confirm the fade stays smooth while the messages appear. Then temporarily add delay(200); at the end of loop() and watch the fade become choppy. That contrast is the lesson of this chapter.
Exercise
A sketch stores a timestamp as unsigned long last and checks if (millis() - last >= 1000). At the moment of the check, last is 4294966296 and millis() has just wrapped around to 200. How much time does the subtraction report, and does the 1000 ms test pass?
Show answer
Distance to the wrap is 2^32 - 4294966296 = 1000, so 1000 ms elapsed before the wrap, plus 200 ms after it. The unsigned subtraction 200 - 4294966296 wraps to 1200. The test 1200 >= 1000 is true, so it passes and the code runs. The rollover has no effect on the result.
Exercise
You want an LED on pin 9 to fade from 0 to 255 over exactly 2 seconds using steps of 5. What interval should you use, and what happens if you use lastStepTime = now and the loop is sometimes late?
Show answer
A fade from 0 to 255 in steps of 5 takes 51 steps (255 / 5). Two seconds divided by 51 is about 39 ms, so use an interval of 39 ms (or 40 ms for simplicity). With lastStepTime = now, any lateness adds to the delay before the next step, so the fade takes slightly longer than 2 seconds. If exact timing matters, use lastStepTime += INTERVAL_MS and guard against large catch-up bursts.
Exercise
Why does a function like updateBlink(now) return early when now - lastBlinkTime < BLINK_INTERVAL_MS, instead of waiting inside the function until the time has passed?
Show answer
Waiting inside the function would be blocking, which is the same problem as delay(). Returning early lets the function finish in microseconds, so loop() can immediately call the other tasks. The timer check is re-evaluated on the next pass.