Learning Goals 5 min
- Combine the
forloop (L01-11) withanalogWrite(L02-02) to fade an LED from off to full over a target duration. - Calculate the fade duration from
steps × delay, and tune step size + delay to land on a desired length. - Chain two fades together — one up, one down — to make a smooth "heartbeat" or "sigh" effect.
Warm-Up 10 min
Yesterday's sketch jumped the LED between three brightness levels with a 1-second pause. The eye saw three distinct states — bright, brighter, brightest. Today we replace those jumps with a smooth ramp so the eye sees one continuous swell of light.
Quick puzzle
Ana wrote this. Predict what the LED does:
const int LED = 9;
void setup() {
pinMode(LED, OUTPUT);
}
void loop() {
for (int v = 0; v <= 255; v++) {
analogWrite(LED, v);
delay(10);
}
}Reveal
The LED fades from off to full bright over about 2.56 seconds (256 steps × 10 ms each), then jumps back to off when the loop ends and loop() restarts. So you see: smooth swell up over 2.5 s, instant snap to dark, swell up again. The fade looks lovely; the snap is jarring. Today we'll fix it with a second loop counting down.
New Concept · One loop = one ramp 20 min
The pattern
A smooth fade is one for loop whose counter is the brightness:
for (int v = 0; v <= 255; v++) {
analogWrite(LED, v);
delay(10);
}Each pass: increase v by 1, write it to the LED, wait 10 ms. 256 passes total. Your eye sees a continuous ramp, not 256 individual steps, because the change between consecutive duty cycles is far below your perception threshold.
The fade duration formula
Total fade time = number_of_steps × delay_per_step. So:
| Step size | Steps in 0→255 | Delay per step | Total fade time |
|---|---|---|---|
| 1 | 256 | 10 ms | 2.56 s |
| 1 | 256 | 5 ms | 1.28 s — fast |
| 1 | 256 | 20 ms | 5.12 s — slow, lamp-like |
| 5 | 52 | 50 ms | 2.60 s — same length, blockier ramp |
| 1 | 256 | 40 ms | 10.24 s — meditation-pace |
To hit a target duration D seconds with single-step fades, use delay = D × 1000 / 256 ms.
Two loops = up and down
The trick from yesterday's warm-up: after the up-ramp, add a second loop that counts down. i-- instead of i++, condition v >= 0 instead of v <= 255:
for (int v = 0; v <= 255; v++) {
analogWrite(LED, v);
delay(10);
}
for (int v = 255; v >= 0; v--) {
analogWrite(LED, v);
delay(10);
}Up over ~2.5 s, then down over ~2.5 s. A full breath cycle. No snap.
What about the eye's curve?
Recall L02-03 — equal duty steps don't look equal to the eye (γ ≈ 2.2). A 0→255 linear fade looks fast at the bottom, slow at the top. That's a feature for some effects (sun rising) and a bug for others (a smooth breath wants more time near the dim end). One quick fix: change the delay per step instead of the step size, so you spend longer in the dim region. We'll leave gamma-corrected tables for L02-06.
Worked Example · A breathing LED 20 min
Step 1 — wiring
Same single-LED circuit as L02-02. Anode (long leg) of the LED → 220 Ω resistor → Arduino pin ~9. Cathode (short leg) → GND rail. Nothing else changes.
Step 2 — the sketch
Save as breathing-led.ino:
// L02-04: breathing LED — fade up, fade down, repeat
const int LED = 9;
const int STEP_DELAY = 10; // ms per step → ~2.5 s up + 2.5 s down
void setup() {
pinMode(LED, OUTPUT);
}
void loop() {
// inhale
for (int v = 0; v <= 255; v++) {
analogWrite(LED, v);
delay(STEP_DELAY);
}
// exhale
for (int v = 255; v >= 0; v--) {
analogWrite(LED, v);
delay(STEP_DELAY);
}
}Step 3 — upload & watch
The LED swells from dark to full bright, then sinks back to dark, then repeats forever. Total cycle ~5 seconds. Feels like a relaxed breath.
Step 4 — change the speed by changing one number
Want a faster breath? Drop STEP_DELAY to 4 ms → full cycle ≈ 2 s. Want a meditation-slow breath? Bump it to 30 ms → full cycle ≈ 15 s. Notice that you only need to change one constant at the top — the loops themselves never move.
Step 5 — a tiny pause at the peak
If you want the LED to hold at full bright before fading down (like the briefest pause at the top of a sigh), add a single delay(200) between the two loops:
// inhale
for (int v = 0; v <= 255; v++) { analogWrite(LED, v);
delay(STEP_DELAY);
}
delay(200); // brief peak hold
// exhale
for (int v = 255; v >= 0; v--) { analogWrite(LED, v);
delay(STEP_DELAY);
}
delay(200); // brief bottom hold (so the next breath isn't instant)That brief hold at each end is the difference between "mechanical fade" and "living breath".
Basic 7 min
Goal: Make the breath last 8 seconds total (4 up + 4 down).
1. Think first (on paper, no typing yet):
- How many brightness steps are there in one ramp, from 0 up to 255?
- If every step waits the same time, how do you get the time for the whole ramp? Turn that round to find the wait per step for 4 seconds.
2. Code it. Open breathing-led from the Worked Example. Change only STEP_DELAY, and show your maths in a comment above it.
3. Upload and observe. Time five full breaths with a stopwatch and divide by five.
It works if: one breath (up and down) takes about 8 seconds.
Challenge 1 7 min
Goal: Asymmetric breath — fade up slowly (3 seconds), then fade down quickly (1 second). Like the LED inhales calmly and exhales sharply.
1. Think first (on paper, no typing yet):
- Your sketch has one
STEP_DELAY, used by both ramps. Can one number give two different speeds? - Work out the wait per step for a 3-second ramp and for a 1-second ramp.
2. Code it. Start from breathing-led. Give each ramp its own named constant.
3. Upload and observe. Time the up and the down separately.
It works if: the LED takes about 3 s to reach full and about 1 s to go dark, over and over, with no jump at the top or bottom.
Questions:
- What did you name your two constants, and what values did you give them? Show the maths. ____
- Swap the two values. What does the breath feel like now? ____
Challenge 2 6 min
Goal: A "heartbeat" — fade up + down in 0.4 s, brief pause, fade up + down again in 0.4 s, longer pause. Should feel like "ba-bum ... ba-bum ...".
1. Think first (on paper, no typing yet):
- The same quick up-and-down happens twice. How could you write it once and use it twice?
- To fit up + down into about 0.4 s, roughly how long can each step wait?
- Write one heartbeat as a list in plain English: what happens, and for how long, in order.
2. Code it. Start from breathing-led, or a new sketch with the LED on ~9.
3. Upload and observe. Show a classmate without telling them what it is meant to be.
It works if: you see two quick pulses close together, then a longer rest, repeating — and a classmate can tell it is a heartbeat.
Questions:
- How long are your short and long pauses? What happened when they were the same length? ____
- Did you write the pulse once, or twice? If once, how? ____
Challenge 3 · The signal lamp 15 min
Build a sketch that fades the LED through three named "moods" with a 1-second pause between each:
- Calm — slow breath, ~6 s up + 6 s down. Repeat 2 breaths.
- Working — medium breath, ~2 s up + 2 s down. Repeat 3 breaths.
- Alert — fast pulse, 0.3 s up + 0.3 s down. Repeat 5 pulses.
The whole sequence runs once per loop() pass, so the entire mood cycle repeats forever.
It works if:
- You can see the three moods are distinctly different in speed.
- You wrote one breath function that is told the up time and the down time, so the main
loop()reads like a script, not a wall of for-loops. - The step delay for each mood is computed from the duration formula, not guessed.
1. Think first (on paper, no typing yet):
- Your breath function is told a time in milliseconds. How does it turn that into a wait per step?
- Write the whole mood cycle as a cue sheet in plain English: which breath, how many times, then the pause.
2. Code it. Start from breathing-led. Get the function working on one breath first, then build the cue sheet in loop().
3. Upload and observe. Time one full mood cycle and check it against your cue sheet.
Recap 5 min
A smooth fade is just a for loop whose counter is fed into analogWrite. Going up = v++; going down = v--. Total fade time = steps × delay. To target a duration D seconds, set the delay to D × 1000 / 256 ms. Wrap a single breath in a function and the main loop() becomes readable. Next lesson we cross-fade three LEDs at once for an RGB colour wheel.
- Fade
- A continuous change in brightness over time, typically achieved by stepping
analogWritevalues inside a for loop. - Ramp
- A one-direction fade — up only, or down only. Two ramps back-to-back make a breath.
- Step size
- How much the counter changes each pass (
v++= 1,v += 5= 5). Bigger steps = blockier ramp. - Asymmetric fade
- Up and down ramps with different speeds. Common in breathing / heartbeat effects.
- Helper function
- A named recipe for a re-used pattern, like
breath(upMs, downMs). Keeps the main loop readable.
Extra Mission 5 min
Part 1 — Design a breathing status light
Chargers and smart speakers often "breathe" a light to show what they are doing. Invent a gadget for your room or school bag. On paper, design how a fading LED shows its state.
Your design must include:
- A name and a one-sentence job for the gadget.
- At least two states, each with its own breath — for example "charging" is slow and "error" is a fast pulse.
- The up time and down time of each breath, in milliseconds.
- The step delay for each one, worked out with
256 steps × delay = time. Show your working.
Part 2 — Make it
Build it on one LED on pin ~9. Write a breath function that is told the up time and the down time. Make loop() play each state for about 10 seconds in turn. Print the state name each time it changes.
Bring back next class: the uploaded sketch, a short video or photo of the LED, and your step-delay working.