Sub topic 7
Fading an LED up and down
This chapter assumes you can write a basic Arduino sketch with setup() and loop(). It also assumes you have wired an LED with a current-limiting resistor to a PWM-capable pin, such as pin 9 on an Uno, and that you know what analogWrite() does. Here you will turn a single brightness value into a smooth, repeating fade. You will also learn where the common errors come from.
The idea: a brightness variable that moves
analogWrite(pin, value) sets the duty cycle on a PWM pin. A value of 0 means always off. A value of 255 means always on. Values in between give proportional average power.
A fade is a brightness value that changes a little on each pass through loop(). Two variables describe it:
brightnessis the current duty value, from 0 to 255.stepis how muchbrightnesschanges on each pass. It is positive while fading up and negative while fading down.
When brightness reaches an end of the range, you reverse the sign of step. That gives a continuous up-and-down "breathing" effect.
A complete blocking fade
This sketch fades an LED on pin 9 up and down. It changes the analogWrite() value in steps of 5 and reverses direction at 0 and 255.
const uint8_t LED_PIN = 9; // PWM-capable pin on an Uno
int brightness = 0;
int step = 5;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
analogWrite(LED_PIN, brightness);
// Reverse direction before leaving the 0..255 range
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
delay(20);
}Walk through the first few passes. brightness starts at 0, so the LED is off. The check sees that 0 + 5 is inside the range, so step stays at 5. brightness becomes 5. After 20 ms the loop runs again and writes 5. This continues until brightness is 255, because 255 is a multiple of 5.
On the pass where brightness is 255, the check sees that 255 + 5 is 260, which is above 255. It flips step to -5. brightness becomes 250, and the fade runs down. At 0 the check sees that 0 + -5 is below 0, so it flips again.
Timing: how long does one fade take?
The fade time follows from the step size and the delay:
- Steps from 0 to 255 with a step of 5: 255 / 5 = 51 steps.
- Time per step: 20 ms (plus a few microseconds for the code).
- One way up: about 51 × 20 ms = 1.02 seconds.
- A full cycle, up and down: about 2 seconds.
You control the speed with two knobs. A smaller step makes the change finer, and a shorter delay() makes it faster. For a given total time, the finest result comes from the smallest step and the correspondingly shortest delay. The limit is the 256 duty levels: a step of 1 is the smallest change analogWrite() can express.
| Step | Delay | Steps per direction | Time per direction | Appearance |
|---|---|---|---|---|
| 5 | 20 ms | 51 | about 1.0 s | Smooth for most eyes |
| 1 | 4 ms | 255 | about 1.0 s | Same speed, finer steps |
| 15 | 20 ms | 17 | about 0.34 s | Fast, may look stepped |
| 1 | 20 ms | 255 | about 5.1 s | Slow, very smooth |
Why the range check looks at the next value
The check is written as brightness + step, not brightness. This is deliberate. If you wrote if (brightness <= 0 || brightness >= 255) and used a step that does not divide 255 evenly, the value could jump past the limit before the check runs. Looking ahead keeps brightness inside 0 to 255 for any step size.
Try a step of 7 to see it. 255 is not a multiple of 7. With look-ahead, the value climbs to 252 (36 × 7), the next addition would give 259, so the direction flips and the value descends. The LED never reaches exactly 255. It peaks at 252, which is imperceptibly dimmer. Without look-ahead, the value would reach 259 and analogWrite() would receive a number outside its range.
Common errors in stepped fades
These are the problems that show up most often when people write their first fade.
Overflow with a `uint8_t` brightness
Using uint8_t brightness looks natural because the range is 0 to 255. It fails here. A uint8_t cannot hold a negative number or a value above 255, so brightness += step wraps around instead. 250 + 10 becomes 4. 3 − 5 becomes 254. The LED then jumps between dim and bright, and your range check may never trigger correctly.
Use int for both brightness and step. The extra byte is irrelevant on a sketch this size.
The fade never reverses, or stops at one end
If step is declared const or the sign flip is missing, the value runs to an end and stays there or wraps. If the check uses == and the step skips the boundary value, the test never matches. The look-ahead comparison with < and > avoids both problems.
Writing the value after the update
The order in the sketch is: write, check, update. If you update first and then write, the first value written is step, not 0. This is usually harmless. It becomes a bug when you need the very first frame to be exactly off, or when another part of the code reads brightness and expects it to match what the LED shows.
Using a non-PWM pin
If the LED is on a pin without PWM, analogWrite() does not fade it. On an Uno, a non-PWM pin is set fully on for values of 128 and above and fully off for values below 128. The symptom is an LED that snaps between off and on halfway through the fade. The Uno's PWM pins are 3, 5, 6, 9, 10 and 11, marked with a tilde (~) on the board. Check the pin before you debug the code.
Changing speed without rewriting the loop
You can name the timing values as constants so the fade is easy to tune. This changes nothing about behavior. It makes the sketch easier to read and adjust:
const uint8_t LED_PIN = 9;
const int STEP_SIZE = 5;
const unsigned long STEP_DELAY_MS = 20;
int brightness = 0;
int step = STEP_SIZE;
void setup() {
pinMode(LED_PIN, OUTPUT);
}
void loop() {
analogWrite(LED_PIN, brightness);
if (brightness + step < 0 || brightness + step > 255) {
step = -step;
}
brightness += step;
delay(STEP_DELAY_MS);
}Keeping STEP_SIZE separate from step is useful. step carries the direction and changes sign. STEP_SIZE is the magnitude you chose, and it never changes.
The cost of `delay()`
The blocking fade works, but it has a structural limit. While delay(20) runs, the processor does nothing else you can control. If you also want to read a button, update a display or run a second fade on another LED, those tasks wait. A button press shorter than the delay can be missed entirely. In this sketch the loop spends almost 100% of its time inside delay().
This matters as soon as the sketch has more than one job. The next chapters replace delay() with a millis() comparison so the loop keeps running. Here is a preview, so you can see the shape of the change. It fades on a schedule while loop() stays free 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 work can run here on every pass through loop()
}The fade logic is identical. Only the "wait" has changed: instead of pausing, the loop asks "has 20 ms passed since the last step?" and skips the update if not. The subtraction now - lastStepTime is safe when millis() wraps around after about 49.7 days, because both values are unsigned long.
Checking your fade
When the fade does not look right, test one thing at a time.
- Confirm the pin supports PWM. Look for the tilde on the board.
- Print
brightnessto the Serial Monitor. AddSerial.begin(9600);tosetup()andSerial.println(brightness);after theanalogWrite()call. You should see 0, 5, 10 and so on up to 255, then back down. - If the printed values are correct and the LED is wrong, the problem is in the wiring: resistor value, LED polarity, or the pin.
- If the printed values are wrong, the problem is in the loop logic. Check the types and the range test.
Serial printing at 9600 baud takes real time, and each line adds a delay of a few milliseconds. Remove it once the fade works, particularly in the millis() version.
Exercise
You change the step in the blocking fade from 5 to 7 and keep the look-ahead check brightness + step < 0 || brightness + step > 255. What is the highest value written to the LED on the way up, and why does it not reach 255?
Show answer
The highest value is 252. The values go 0, 7, 14, and so on, which are multiples of 7. 36 × 7 = 252. The next value would be 259, which is above 255, so the check flips the step and the fade turns around. 255 is not a multiple of 7, so the sequence never lands on it. The look-ahead check stops the value from leaving the 0 to 255 range.
Exercise
A fade uses uint8_t brightness and int step = 5, with no look-ahead check. When brightness is 253 and the code runs brightness += step, what value does brightness hold afterward, and what does the LED do?
Show answer
253 + 5 = 258, which wraps modulo 256 to 2. brightness becomes 2, so the LED jumps from nearly full brightness to nearly off. The fade shows a sudden drop instead of reversing smoothly. Using an int and a range check fixes it.
Exercise
You want a fade from 0 to 255 and back that takes about 4 seconds in total, using a step of 1. What delay per step do you need?
Show answer
A full cycle has 255 steps up and 255 steps down, about 510 steps. 4000 ms / 510 is about 7.8 ms, so use a delay of 8 ms. That gives about 4.1 seconds per cycle.