Fading an LED with PWM
Use a loop and analogWrite together to produce a smooth, continuous breathing fade instead of fixed brightness steps.
You'll need: the same LED-on-a-PWM-pin wiring from Lesson ard-08.
Lesson ard-08 ended by suggesting a loop that ramps brightness up and down — this lesson builds that properly, introducing the for loop, one of the most useful pieces of syntax for repeating an action with a changing value each time.
void setup() {
pinMode(9, OUTPUT);
}
void loop() {
for (int level = 0; level <= 255; level++) {
analogWrite(9, level);
delay(8);
}
for (int level = 255; level >= 0; level--) {
analogWrite(9, level);
delay(8);
}
}
A for loop has three parts, separated by semicolons: a starting value (int level = 0), a condition checked before each repeat (level <= 255), and an action performed after each repeat (level++, which increases level by one). Together, this counts level from 0 to 255, calling analogWrite(9, level) at every step along the way — exactly 256 brightness steps, each held for 8 milliseconds, producing a fade that takes just about two seconds up, then two seconds back down.
Try changing the delay(8) value: a smaller number fades faster, a larger number fades slower — a simple, safe way to get comfortable adjusting a for loop's behavior before writing one from scratch yourself.