Learning Goals 5 min
- Build the Cluster F capstone: three separate LED patterns running at three different speeds in one loop, with a button to swap between "shows".
- Apply tick functions (L02-36), debouncing (L02-37), and per-pattern state to a non-trivial real-time animation system.
- Refactor the result into a clean "pattern" abstraction — each pattern is a function that knows how to advance itself by one frame given the current time.
Warm-Up 10 min
Cluster F started with delay-is-bad and ends with this: a small piece of visual art that you couldn't have built before the cluster. Three LEDs, three completely independent animations, all running in real time off one loop. A button switches between three "shows". Total sketch size: under 150 lines. Total delay() calls: zero.
Three patterns to plan
For each LED we'll define a pattern function. Examples:
- Blink: on for X ms, off for Y ms, repeat.
- Breathe: PWM fade up over X ms, fade down over Y ms.
- Heartbeat: 100 ms on, 100 ms off, 100 ms on, 700 ms off (the classic two-thump pattern).
- Pulse-train: three quick flashes, long pause, repeat.
- Strobe: very fast on/off (30 ms / 30 ms) — like a club light.
New Concept · One pattern, many instances 20 min
The shape of a pattern function
Each pattern is "a function that you call once per loop iteration, that updates an LED's state based on the current time". We'll standardise the signature:
void patternBlink(int pin, unsigned long onMs, unsigned long offMs);
void patternBreathe(int pin, unsigned long periodMs);
void patternHeartbeat(int pin);Each function reads millis() and decides what the LED should be doing right now. None of them store any state — they compute everything from the current time. That makes them stateless and trivial to compose.
Stateless blink
void patternBlink(int pin, unsigned long onMs, unsigned long offMs) {
unsigned long period = onMs + offMs;
unsigned long phase = millis() % period;
digitalWrite(pin, phase < onMs ? HIGH : LOW);
}One line of arithmetic. The current phase within the period decides on/off. No previousMillis, no ledState. Re-entrant: call it as often as you like; the LED state is recomputed from millis() every time.
Stateless breathe
void patternBreathe(int pin, unsigned long periodMs) {
unsigned long phase = millis() % periodMs;
int half = periodMs / 2;
int brightness;
if (phase < (unsigned long)half) {
brightness = map(phase, 0, half, 0, 255); // fading up
} else {
brightness = map(phase, half, periodMs, 255, 0); // fading down
}
analogWrite(pin, brightness);
}A triangle wave: up for half the period, down for half. Same pattern, no state. Plug it on any PWM pin.
Stateless heartbeat
The two-thump cardiac pattern: 100 ms on, 100 ms off, 100 ms on, 700 ms off (total period 1000 ms). Four phases, look up which one we're in:
void patternHeartbeat(int pin) {
unsigned long phase = millis() % 1000;
bool on = (phase < 100) || (phase >= 200 && phase < 300);
digitalWrite(pin, on ? HIGH : LOW);
}Tweak the four numbers for different cardiac rhythms.
Composing them in a "show"
A show is just a set of three pattern calls. Switching shows is switching which function gets called:
enum Show { SHOW_BASIC, SHOW_CHASE, SHOW_PARTY };
Show show = SHOW_BASIC;
void runCurrentShow() {
switch (show) {
case SHOW_BASIC:
patternBlink(LED1, 500, 500);
patternBreathe(LED2, 2000);
patternHeartbeat(LED3);
break;
case SHOW_CHASE:
patternBlink(LED1, 100, 200);
patternBlink(LED2, 100, 200); // intentionally same as LED1 → in sync
patternBlink(LED3, 100, 200);
break;
case SHOW_PARTY:
patternBlink(LED1, 50, 50);
patternBreathe(LED2, 500);
patternBlink(LED3, 80, 120);
break;
}
}One function per show. The whole show changes when you flip an enum. No tear-down, no state reset, no race conditions — because the patterns are stateless.
Worked Example · Three patterns, three shows 25 min
Step 1 — wiring
| Component | Pin |
|---|---|
| LED1 (with 220 Ω) | D9 (PWM) |
| LED2 (with 220 Ω) | D10 (PWM) |
| LED3 (with 220 Ω) | D11 (PWM) |
| Show-cycle button | D2 (INPUT_PULLUP, to GND) |
Step 2 — the sketch
Save as multi-led-choreography.ino:
// L02-38: Multi-LED Choreography — Cluster F capstone
// Three LEDs running independent patterns. Button cycles between 3 shows.
const int LED1 = 9, LED2 = 10, LED3 = 11;
const int BUTTON = 2;
enum Show { SHOW_BASIC, SHOW_CHASE, SHOW_PARTY };
Show show = SHOW_BASIC;
const char* showName[] = {"BASIC", "CHASE", "PARTY"};
// ---- Stateless patterns ----
void patternBlink(int pin, unsigned long onMs, unsigned long offMs) {
unsigned long period = onMs + offMs;
unsigned long phase = millis() % period;
digitalWrite(pin, phase < onMs ? HIGH : LOW);
}
void patternBreathe(int pin, unsigned long periodMs) {
unsigned long phase = millis() % periodMs;
int half = periodMs / 2;
int brightness = (phase < (unsigned long)half)
? map(phase, 0, half, 0, 255)
: map(phase, half, periodMs, 255, 0);
analogWrite(pin, brightness);
}
void patternHeartbeat(int pin) {
unsigned long phase = millis() % 1000;
bool on = (phase < 100) || (phase >= 200 && phase < 300);
digitalWrite(pin, on ? HIGH : LOW);
}
void patternChase(int pin, int slot, int totalSlots, unsigned long stepMs) {
unsigned long currentSlot = (millis() / stepMs) % totalSlots;
digitalWrite(pin, currentSlot == (unsigned long)slot ? HIGH : LOW);
}
// ---- Show dispatch ----
void runShow() {
switch (show) {
case SHOW_BASIC:
patternBlink(LED1, 500, 500);
patternBreathe(LED2, 2000);
patternHeartbeat(LED3);
break;
case SHOW_CHASE:
patternChase(LED1, 0, 3, 150);
patternChase(LED2, 1, 3, 150);
patternChase(LED3, 2, 3, 150);
break;
case SHOW_PARTY:
patternBlink(LED1, 50, 80);
patternBreathe(LED2, 400);
patternBlink(LED3, 120, 60);
break;
}
}
// ---- Debounced button ----
struct Button {
int pin;
unsigned long lastChange;
int rawState, stableState, prevStable;
bool justPressed;
void begin(int p) {
pin = p;
pinMode(pin, INPUT_PULLUP);
rawState = stableState = prevStable = digitalRead(pin);
lastChange = millis();
justPressed = false;
}
void tick() {
int now = digitalRead(pin);
if (now != rawState) { rawState = now;
lastChange = millis();
}
justPressed = false;
if (millis() - lastChange >= 50 && rawState != stableState) {
prevStable = stableState;
stableState = rawState;
if (stableState == LOW && prevStable == HIGH) justPressed = true;
}
}
};
Button btn;
void setup() {
pinMode(LED1, OUTPUT);
pinMode(LED2, OUTPUT);
pinMode(LED3, OUTPUT);
btn.begin(BUTTON);
Serial.begin(9600);
Serial.print("Show: ");
Serial.println(showName[show]);
}
void loop() {
btn.tick();
if (btn.justPressed) {
show = (Show)((show + 1) % 3);
// Clear the LEDs before the next show — fast wipe avoids inheriting
// a fade or a HIGH from the previous show.
analogWrite(LED1, 0);
analogWrite(LED2, 0);
analogWrite(LED3, 0);
Serial.print("Show: ");
Serial.println(showName[show]);
}
runShow();
}Step 3 — upload, watch the BASIC show
LED1 blinks at 1 Hz (500/500). LED2 breathes slowly (2 s up + down). LED3 does the heartbeat (two thumps per second). All three running together. Look at it. This is what you couldn't build cleanly before Cluster F.
Step 4 — press the button → CHASE
All three LEDs now light up in sequence — LED1 for 150 ms, then LED2 for 150 ms, then LED3 for 150 ms, repeating. The classic three-LED chase, executed by three independent patterns that happen to share the same step rate and totalSlots. Not coupled — just coincidentally synchronised.
Step 5 — press → PARTY
Strobe + fast breathe + asymmetric strobe. Looks like a tiny dance floor. Total chaos but controlled.
Step 6 — press → back to BASIC
The cycle closes. Note how snappy the button is — press while in a fast strobe and the show changes immediately, even though the loop is busy running patterns.
Basic 7 min
Goal: Add a fourth show — "OFF". All three LEDs off. Useful as the "sleep" mode.
1. Think first (on paper, no typing yet):
- List every place the shows are named or counted. What has to change in each one?
- In OFF, what must happen to each LED? Why is it not enough just to stop updating them?
2. Code it. Open your Worked Example sketch.
3. Upload and observe. Press the button eight times, slowly.
It works if:
- The four shows come round in order, twice.
- In OFF, all three LEDs are fully dark, not frozen part-way bright.
- The Serial Monitor shows the new show's name.
Questions:
- What did the LEDs do in OFF before you made it switch them off? ____
Challenge 1 7 min
Goal: Design a fifth pattern of your own. Possibilities: random twinkle (LED on/off randomly with a long bias toward off); sine wave (smoother than the triangle breathe); Morse pulse (long-short-short-... sequence for a chosen letter).
1. Think first (on paper, no typing yet):
- Choose a pattern. Draw a graph of what one LED's brightness does over 2 seconds.
- The other patterns work out where they are in their cycle without
delay(). How will yours? - Write one sentence that starts "It works if…" before you code.
2. Code it. Write it as a new pattern function, then give it its own show.
3. Upload and observe. Compare the LEDs with your graph.
It works if:
- The LEDs match your graph and your sentence.
- There is no
delay()in your pattern. - The button still switches shows straight away.
Questions:
- Which pattern did you choose? What was hardest to get right? ____
Challenge 2 6 min
Goal: Add a crossfade between shows. Instead of instantly switching, gradually fade out the old show's LEDs while fading in the new show over 1 second.
1. Think first (on paper, no typing yet):
- During the 1 second, what must the sketch remember? Think about where it came from and when the change started.
- One LED is at 200 in the old show and 50 in the new show. What should it be halfway through the change?
- Your patterns write to the pins themselves. What would have to change so you could mix two of them?
2. Code it. Start from your Worked Example sketch. This is a bigger change, so plan it on paper first.
3. Upload and observe. Press the button and watch for one second.
It works if:
- Over about 1 second, the old show fades out while the new show fades in.
- Nothing jumps suddenly at the start or end of the change.
- The button still works during a change.
Questions:
- What did you have to change in your pattern functions? ____
Challenge 3 · Two shows to a spec 15 min
A client wants two new shows added to the worked example. Build them exactly to this spec.
- SUNRISE: all three LEDs breathe with a 3000 ms period. LED2 runs 1000 ms behind LED1. LED3 runs 1000 ms behind LED2.
- ALERT: all three LEDs flash together three times — 100 ms on, 100 ms off. Then they stay dark for 1000 ms, and the pattern repeats.
You will need:
- A new pattern,
patternBreatheLate(pin, periodMs, lateMs). It breathes likepatternBreathe(), butlateMsbehind. - A new pattern for ALERT, built on
millis() % periodlikepatternHeartbeat(). - Two new
Showvalues, two new names inshowName[], and a bigger number in the button handler's% 3.
This is what ALERT should look like:
It works if SUNRISE looks like a wave rolling from LED1 to LED3, ALERT gives three quick flashes then a pause, and the button still reaches every show.
Recap 5 min
Cluster F closes with the Multi-LED Choreography — three LEDs, three independent patterns, three switchable shows, one button, zero delay. The architectural insight is the stateless pattern function: a function that takes the current millis() reading and decides what the LED should look like right now. Stateless patterns trivially compose into shows, switch instantly between shows, and don't fight each other. Combined with the L02-37 debouncer and the L02-36 tick discipline, you can now build any "many timed things in one loop" system on a single UNO. Cluster G picks up next with EEPROM and SD cards — adding persistence to everything we've built.
- Choreography
- The deliberate orchestration of multiple LEDs (or actuators) over time to produce a coherent visual effect. The same word arts-people use for dance.
- Stateless pattern
- A function that computes the output entirely from the current time, with no internal memory of past calls. Trivially composable and re-entrant.
- Modular arithmetic with millis()
millis() % periodgives the phase within a recurring period. The base trick of every stateless pattern. Wraps cleanly across the 49-day millis() wrap.- Show / scene
- A named combination of which patterns are running on which LEDs. Switching shows = switching the dispatch case.
- Pattern function signature
- Standardising how patterns are called (e.g.
patternBlink(pin, onMs, offMs)) so they can be swapped freely without rewriting the show dispatch. - Triangle wave / sine wave
- Two common brightness shapes for breathing LEDs. Triangle is cheaper to compute (just arithmetic); sine is smoother visually but uses
sin(). - Crossfade
- A smooth transition between two shows by mixing their outputs over a short period. Requires patterns to return brightness rather than write pins directly.
- Cluster F discipline
- The four habits Cluster F instilled: no
delay, one tick per task,millis()with safe-subtract, debounce all buttons. The foundation of every L3 project.
Extra Mission 5 min
Part 1 — Design a light show for a real object
Pick an everyday object that could use a light show. Ideas: a birthday cake topper, a bike, a night-light, a race finish line. On paper, design one show for it with three LEDs.
Your design must include:
- The show's name and the mood or message it gives.
- Each LED's pattern — blink, breathe, heartbeat, chase or your own — with its timings in ms.
- Why those timings fit the mood. Fast feels urgent; slow feels calm.
Part 2 — Make it
Add your show to the worked example as a new Show value with its own case in runShow(). Use only stateless pattern functions driven by millis(). Check the button still reaches every show.
Bring back next class: your design, your hw-l02-38.ino sketch, and a short video of your show running.