Sub topic 9
Fading Without Blocking: Using `millis()` Instead of `delay()`
This chapter assumes that you know the Arduino setup() and loop() functions, can use pinMode() and digitalWrite(), and understand that analogWrite() controls PWM brightness on a supported pin.
Why `delay()` blocks the program
A simple fade often uses delay():
analogWrite(9, brightness);
delay(20);During the 20-millisecond delay, the Arduino does not run the rest of your loop() code. It cannot read a button, check a sensor, or update another output until the delay ends.
This is called blocking. A blocking operation prevents other work from running.
The millis() function provides a non-blocking alternative. It returns the number of milliseconds since the Arduino started the current program. Your code can compare the current time with the time of the last brightness update.
The timing pattern
The basic pattern is:
- Read the current time.
- Check whether enough time has passed.
- Update the output if the interval has elapsed.
- Continue with the rest of
loop().
A time interval is the amount of time between two events. In this example, the interval controls how often the brightness changes.
A non-blocking fade
The following sketch fades an LED on pin 9 up and down. It leaves the rest of loop() available for other tasks.
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 code can run on every pass through loop().
}The INTERVAL_MS constant sets the time between brightness changes. The code changes brightness by 5 every 20 milliseconds. A complete fade takes about:
255 / 5 × 20 ms × 2 = 2040 msThe multiplication by 2 accounts for the rising and falling parts of the fade.
The condition brightness + step < 0 || brightness + step > 255 detects when the next value would leave the valid PWM range. When that happens, the code reverses step.
Why subtract the times?
The expression below is the usual Arduino timing pattern:
if (now - lastStepTime >= INTERVAL_MS)Both variables are unsigned long. Unsigned subtraction continues to work correctly when millis() eventually overflows and returns to zero. Comparing absolute times directly, such as now >= lastStepTime + INTERVAL_MS, can fail around that rollover.
The assignment lastStepTime = now starts the next interval after the update. If other code takes a long time to run, the next update waits for a complete interval. For most LED fades, this behavior is acceptable.
> callout tip > Keep time values as unsigned long, and compare elapsed time by subtracting the previous timestamp from the current timestamp.
Choosing the interval
A smaller interval makes the fade update more often, but it does not automatically make the fade smoother. The visible result depends on both the interval and the brightness step.
| Interval | Brightness step | Approximate full fade time |
|---|---|---|
| 20 ms | 5 | 2.04 seconds |
| 10 ms | 2 | 2.55 seconds |
| 30 ms | 10 | 1.53 seconds |
If the step is large, the LED may appear to jump between brightness levels. If the interval is too long, the eye may notice each update. An interval between 10 and 30 milliseconds is a useful starting point.
Exercise
Exercise
Why does replacing delay(20) with a millis() comparison allow a button-reading task to run during the fade?
Show answer
delay() pauses the program, but a millis() comparison checks elapsed time and then lets loop() continue immediately when the interval has not elapsed.