class: center, middle, inverse, title-slide .title[ # Stop the Light: Never Miss a Tap ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### Appendix — Stop the Light, part 3 of 3 (planned for Class 24) ] --- <style> .code-tight .remark-code { font-size: 14px; line-height: 1.2; } .code-tighter .remark-code { font-size: 12.5px; line-height: 1.15; } .remark-slide-content table { width: 100%; } .emphasis { top: 0; left: 0; margin-top: 12px; } .tool { display: inline-block; background: #364F6B; color: #fff; border-radius: 6px; padding: 1px 10px; font-weight: 700; font-size: 0.85em; } .mission { display: inline-block; background: #B5452B; color: #fff; border-radius: 6px; padding: 1px 10px; font-weight: 700; font-size: 0.85em; } .done { background: #EAF1F8; border-left: 5px solid #364F6B; border-radius: 6px; padding: 8px 14px; margin-top: 10px; } .timeline { font-family: 'Source Code Pro', monospace; font-size: 17px; background: #EAF1F8; border-radius: 8px; padding: 10px 16px; line-height: 1.6; } </style> # Learning Targets .lt-box[ - Explain why a program inside `delay()` can't notice a button. - Time things with **`millis()`** so `loop()` never stops watching. - Keep the light's position in **variables** instead of a `for` loop. - Finish a complete game: lives, game over, a high score. ] .eu-label[Essential Understanding:] `delay()` makes the board deaf: while it waits, nothing else happens. A program that has to watch and wait at the same time never waits. It goes around `loop()` thousands of times a second, and each time asks *"is it time yet?"* That means `loop()` can't remember where the light is, so variables have to. --- # Agenda .agenda-box[ 1. Last class's bug: what was the board doing? 2. .tool[Tools] The clock, and remembering where you are 3. .mission[Mission 7] The light moves with no `delay()` 4. One tap, three hits? 5. .mission[Mission 8] The tap test 6. .mission[Mission 9] Lives, game over, high score 7. **Arcade:** play each other's games 8. Sign-off with Dr. Alvear, then wrap-up ] .center[ Start from **your** Class 23 program. Save a copy first: today's change touches almost every line of `loop()`. ] --- class: small-font # Last class's bug: what was the board doing? With the light at 300 ms per LED, here is one trip through a step: .timeline[ light on → `delay(300)` ............................................ → **read button** → light off<br> ↑ your quick tap lands here: nobody is looking ] .pull-left.w48[ The button is read for **an instant** at the end of each step. For the other **299.99 ms**, the board is inside `delay()`, doing nothing at all. - A **held** press is still down when the board looks: counted. - A **quick tap** starts and ends inside the `delay()`: never seen. ] .pull-right.w48[ .emphasis[ **Waiting and watching can't both happen in `delay()`.** The fix isn't a shorter delay. It's **no delay**: go around `loop()` as fast as possible, and each time, ask two questions: 1. Is the button **just pressed**? 2. Is it **time** to move the light? ] ] --- class: small-font # .tool[Tool] The clock: is it time yet? .pull-left.w50.code-tight[ ```cpp const int BTN = 2; unsigned long lastBlink = 0; bool ledOn = false; bool wasPressed = false; void setup() { pinMode(13, OUTPUT); pinMode(BTN, INPUT_PULLUP); Serial.begin(9600); } void loop() { // question 1: time to blink? if (millis() - lastBlink >= 500) { ledOn = !ledOn; digitalWrite(13, ledOn); lastBlink = millis(); // write down when } // question 2: just pressed? bool pressed = (digitalRead(BTN) == LOW); if (pressed && !wasPressed) { Serial.println("Heard you!"); } wasPressed = pressed; } ``` ] .pull-right.w46[ The board's **L** light blinks every half second, **and** every tap prints instantly, however quick. You met this in Class 20: `millis()` is a stopwatch that started when the board powered on. Two moves, always together: 1. **Write down when:** `lastBlink = millis();` 2. **Ask how long since:** `millis() - lastBlink` There's no `delay()` anywhere, so `loop()` runs **thousands of times** a second. Almost every trip, the answer to *"time yet?"* is **no**, and that's fine. .font-small[ **Always `unsigned long`** for anything holding `millis()`. An `int` breaks after 33 seconds. ] ] --- class: small-font # .tool[Tool] Remember where you are .pull-left.w48.code-tight[ ```cpp int level = 0; // where we are: 0 to 3 int change = 1; // +1 going up, -1 going down unsigned long lastTick = 0; void loop() { if (millis() - lastTick >= 300) { level = level + change; if (level == 3 || level == 0) { change = -change; // turn around } for (int s = 0; s <= level; s++) { Serial.print("*"); } Serial.println(); lastTick = millis(); } } ``` ] .pull-right.w48[ Prints a pendulum: `**`, `***`, `****`, `***`, `**`, `*`, `**`... Your Class 22 light lived in a `for` loop: **`i`** knew where it was. With no `delay()`, a `for` loop over the LEDs finishes in microseconds. It can't hold the light anymore. So **two variables outside every function** do the remembering: | Variable | Remembers | |---|---| | `level` | where we are now | | `change` | which way we're going | Each tick: **move one**, and **turn around at the ends**. `||` is **or**. .font-small[ This `for` is fine: it just prints the stars, all at once, with no waiting inside. ] ] --- class: small-font # .mission[Mission 7] The light moves with no `delay()` .pull-left.w48[ Rewrite the bouncing so that **`loop()` never waits**: - the lit LED's **number** and its **direction** live in variables at the top; - each trip through `loop()`, ask *"time to move?"*. If yes: turn the old LED off, move one, turn around at the ends, turn the new one on; - each trip, ask *"just pressed?"*. If yes: is the lit LED the target? Hit or miss, just like Class 23. Your score, speed-up and sounds from Class 23 move across with almost no change. .font-small[ `tone(pin, pitch, ms)` doesn't wait, so your sounds are fine. Look for any other `delay()` in the path of a normal game. ] ] .pull-right.w48[ .done[ **Done when:** - the light bounces **1 2 3 4 5 4 3 2 1...** as before, with no double-length ends; - hits, misses, the score and the speed-up all work; - **no `delay()`** runs while the game is being played. ] .font-small[ **Plan it in English first.** Two questions per trip, in whichever order you like. Which variables does each question need? ] ] --- class: small-font # One tap, three hits? .pull-left.w48[ Groups will see this today: **one quick tap scores 2 or 3 hits.** A button is two pieces of metal. When they meet, they **bounce** for a few milliseconds: touch, apart, touch, apart, then stay. Your Class 23 program looked at the button once every 300 ms, so it never noticed. Now `loop()` looks **thousands of times a second**, and it sees every bounce as a new press. .font-small[ The 555 in Class 13 ignored bounces on its own: once triggered, it couldn't be triggered again until the pulse ended. Your program needs a rule like that. ] ] .pull-right.w48.code-tight[ **One answer per question:** a quiz buzzer that takes one answer, then waits for the next question. ```cpp bool answered = false; void nextQuestion() { answered = false; // a fresh chance } void buzz() { if (answered) return; // already took one answered = true; Serial.println("Answer taken"); } ``` For your game: **one press per LED.** What's the "next question"? *When the light moves.* ] --- class: small-font # .mission[Mission 8] The tap test .pull-left.w48[ Your game should now hear **every** tap, and **only once**. Test it like Class 23's bug hunt, at the **slowest** speed, on the target: 1. **10 quick taps**, one per visit of the light; 2. **press and hold** across several LEDs; 3. **mash** the button while the target is lit. Write the results in your notebook beside last class's. ] .pull-right.w48[ .done[ **Done when:** - 10 quick taps on the target give **exactly 10 hits**; - a held press scores **once**; - mashing on one LED scores **once**. ] .font-small[ **Not passing?** Print what the program sees on every press: the LED number, whether it was already answered, and `millis()`. Two lines a few ms apart are a bounce. ] ] --- class: small-font # .mission[Mission 9] Lives, game over, high score .pull-left.w50[ - You start with **3 lives** (make it a `const`). A miss costs one, and prints how many are left. - At **0 lives**: a **game-over tune**, the final score, and whether it's a **new high score**. - The **high score** lasts until the board is unplugged. - Then wait for a press to start a **new game**: score 0, full lives, the **knob's** starting speed. .font-small[ **A tune is two arrays:** one of notes, one of lengths, and a `for` loop that plays note `i` for length `i`. During game over, a `delay()` is fine: nothing else needs watching. ] ] .pull-right.w46[ .done[ **Done when:** - a full game runs from start to **game over** and into a **new game** without touching the board's reset button; - the high score **survives** into the next game, and only goes up; - the press that starts a new game **isn't** counted as a miss. ] .font-small[ **Lives went to −1 and the game kept going?** Check how you test for game over. ] ] --- class: small-font # Arcade .pull-left.w48[ **The last 15 minutes.** 1. Leave your game running, knob on a **medium** speed. 2. Half of each group stays to explain the game. The other half goes and **plays** at the other tables. 3. Switch halfway. **Best score at each table** goes on the board. ] .pull-right.w48[ **While you play someone else's game:** - Do taps ever get missed? - What's the best sound you heard? The best idea? - One thing you'd steal for your own game. .emphasis[ Every group wrote this from an empty file. They all work differently, and they all work. ] ] --- class: small-font # Sign-off, then make it yours .pull-left.w50[ **Sign-off with Dr. Alvear: 1,000 points** | Mission | Show | Points | |---|---|---| | 7 | the game, with no `delay()` during play | 400 | | 8 | the tap test: 10 taps, 10 hits; one per press | 200 | | 9 | lives, game over, high score, new game | 400 | That's the last **1,000** of the project's **3,000**. ] .pull-right.w46[ **Finished early? Pick one.** - **Two players:** take turns, and the Serial Monitor keeps both scores. - **Moving target:** after every 5 hits, the target becomes a different LED. - **Lives you can see:** before each game, light one LED per life. - **Speed you can feel:** the hit sound gets higher as the game gets faster. ] --- class: small-font # Stuck? .pull-left.w48[ | What you see | Usual cause | |---|---| | The light races, every LED at once | `lastMove = millis();` is missing, so it's always time | | The light never moves | `lastMove` set every trip, not only when it moves | | Fine for 30 s, then strange | an `int` holding `millis()`: use `unsigned long` | | Goes off the end, or an LED stays dark | turned around one step too late: check `== 4` / `== 0` | | Two LEDs on at once | the old LED isn't turned off before moving | ] .pull-right.w48[ | What you see | Usual cause | |---|---| | One tap, two or three hits | button bounce: one press per LED | | Taps still missed | a `delay()` is left in the game's path | | Game never ends | lives went below 0 and you test `== 0`. Try `<= 0`, or stop at 0 | | New game starts with a miss | the restart press was counted. Update `wasPressed` | | High score always equals the score | `best = score` without checking `>` first | ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - In two sentences: why couldn't the Class 23 game hear a quick tap, and what changed today? - Your tap test results, beside last class's. - The variables your game remembers now. For each one: what it remembers, and where it changes. - Look at your Class 22 code and your code today. What would you do differently if you started again? ] .center[ **Stop the Light is finished:** 3,000 points, and a game you wrote from an empty file. ]