class: center, middle, inverse, title-slide .title[ # Stop the Light: Make It a Game ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### Appendix — Stop the Light, part 2 of 3 (planned for Class 23) ] --- <style> .code-tight .remark-code { font-size: 14px; line-height: 1.2; } .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; } </style> # Learning Targets .lt-box[ - Play sounds of a chosen pitch and length with **`tone()`**. - Count a button press **once**, however long it's held. - Use what your program already knows (which LED is lit, the score, the speed) to decide what happens when the button is pressed. - Find a bug, describe exactly when it happens, and explain why. ] .eu-label[Essential Understanding:] A game is a program that keeps track of what's going on: which LED is lit, the score, how fast it moves. When the button is pressed, the program doesn't look at the LEDs to find out which one is on. It already knows, because it's the one that turned it on. --- # Agenda .agenda-box[ 1. Wire it: a button and a speaker 2. .tool[Tools] `tone()`, and a press that counts once 3. .mission[Mission 4] A start-up sound and a button that works 4. .tool[Tool] Which LED is lit? And functions that take a number 5. .mission[Mission 5] Hit or miss 6. .mission[Mission 6] Score, and faster after every hit 7. **Bug hunt:** does every press count? 8. Sign-off with Dr. Alvear, then wrap-up ] .center[ Start from **your** Class 22 program. Everything you add today goes on top of it. ] --- class: small-font # Wire it: a button and a speaker .pull-left.w52[ <img src="assets/schematics/stop-light-game.svg" alt="The Class 22 circuit plus: pin 7 through a 220 ohm and a 100 ohm resistor to a speaker and then ground; pin 2 through a pushbutton to ground" style="width:100%;max-height:420px;"/> ] .pull-right.w44[ **Keep everything from Class 22.** Add two things: 1. **Unplug the board.** 2. **The button:** across the centre trench. One leg to **pin 2**, the **diagonally opposite** leg to the **GND rail**. No resistor: `INPUT_PULLUP` gives you one. 3. **The speaker:** **pin 7 → 220 Ω → 100 Ω → speaker → GND rail**. .font-small[ **Why two resistors?** A pin should give no more than about 20 mA. 5 V ÷ 320 Ω ≈ 15 mA. The 220 Ω alone would be about 22 mA, a little too much. Same as the *Operation* game. ] ] --- class: small-font # .tool[Tool] `tone()`: make a sound .pull-left.w48.code-tight[ ```cpp const int BUZZ = 7; void setup() { // a doorbell: ding... dong tone(BUZZ, 659, 300); // E, 300 ms delay(350); tone(BUZZ, 523, 600); // C, 600 ms } void loop() { } ``` ] .pull-right.w48[ `tone(pin, pitch, ms)` plays a square wave: **pitch** in Hz (vibrations per second), for **ms** milliseconds. Some pitches to start from: **147** (low, a "wrong" sound) · **523** C · **659** E · **784** G · **1047** (high C, a "yes" sound). .emphasis[ `tone()` **doesn't wait.** It starts the sound and your program moves on right away. To play two notes in a row, you need the `delay()` between them, or the second note cuts off the first. ] .font-small[ `tone(pin, pitch)` with no time plays forever, until `noTone(pin)`. ] ] --- class: small-font # .tool[Tool] A press that counts once .pull-left.w50.code-tight[ ```cpp const int BTN = 2; int presses = 0; bool wasPressed = false; // last trip void setup() { pinMode(BTN, INPUT_PULLUP); Serial.begin(9600); } void loop() { bool pressed = (digitalRead(BTN) == LOW); if (pressed && !wasPressed) { // just pressed presses++; Serial.print("Pressed "); Serial.print(presses); Serial.println(" times"); } wasPressed = pressed; // remember delay(10); } ``` ] .pull-right.w46[ `digitalRead(BTN) == LOW` means **"pressed right now"**, so it's true for every trip through `loop()` while your finger is down. Hold it for one second and that's a hundred "presses". You've seen the fix before: it's the dispenser's **`wasThere`**. Compare **now** with **last trip**: | `wasPressed` | `pressed` | | |---|---|---| | false | **true** | **just pressed**: count it | | true | true | still held: ignore it | .font-small[ `INPUT_PULLUP` means **pressed reads LOW**. Not pressed reads HIGH. ] ] --- class: small-font # .mission[Mission 4] A start-up sound and a button that works .pull-left.w48[ Add to your Class 22 program: - a **start-up sound** when the board starts (two or three notes, your choice); - the **button** on pin 2, with `INPUT_PULLUP`; - every **press** prints `pressed` to the Serial Monitor, **once**, no matter how long you hold it. Keep the light bouncing the whole time. .font-small[ Give your pins names at the top: `const int BUTTON = 2;` and `const int SPEAKER = 7;`. You'll type them a lot today. ] ] .pull-right.w48[ .done[ **Done when:** - pressing the board's **reset** button plays your start-up sound; - one press prints `pressed` **once**, even if you hold it for three seconds; - the light still bounces. ] .font-small[ **Notice something?** Some presses may not print at all. Write down when that happens. It's today's bug hunt. ] ] --- class: small-font # .tool[Tool] Which LED is lit? .pull-left.w50[ When the button is pressed, how does your program know which LED is on? **It doesn't need to look.** In your bouncing code, a variable already says which LED is lit: the **`i`** in your `for` loops. `LEDS[i]` is on, so the lit LED is number `i`. | `i` | 0 | 1 | **2** | 3 | 4 | |---|---|---|---|---|---| | pin | 8 | 9 | **10** | 11 | 12 | The target is **`i == 2`**, not `i == 10`. .font-small[ So the button check goes **inside** the `for` loop, while `i` still means something. ] ] .pull-right.w46.code-tight[ **Two loops, one job?** Put the job in a **function that takes a number**: ```cpp void beep(int times) { for (int n = 0; n < times; n++) { tone(7, 784, 100); delay(200); } } // somewhere else: beep(3); // three beeps beep(1); // one beep ``` `times` is a **parameter**: a variable that gets its value when you call the function. Your two `for` loops could both call one function, something like `step(i)`. ] --- class: small-font # .mission[Mission 5] Hit or miss .pull-left.w48[ Press the button **while the target is lit**: a **hit**. Press it while any other LED is lit: a **miss**. Write it in plain English first, as comments: ```cpp // light LED i // wait // if the button was just pressed: // if i is the target: hit // otherwise: miss // turn LED i off ``` A hit and a miss each get their **own sound** and their own message on the Serial Monitor. You choose them. ] .pull-right.w48[ .done[ **Done when,** with the knob on its **slowest** speed: - press on the target **3 times**: 3 hit sounds, 3 `Hit!`s; - press on other LEDs **3 times**: 3 miss sounds, 3 `Miss`es; - holding the button down never scores twice. ] .font-small[ **Hint:** if your presses only count when you hold the button a little, that's not your hit-or-miss code. It's the bug hunt. Hold a little longer for now. ] ] --- class: small-font # .mission[Mission 6] Score, and faster after every hit .pull-left.w48[ **A hit:** - adds 1 to the **score**, and prints it; - makes the light **faster**. You choose how much: 20 ms off each step? 15% off? - but never faster than a **limit** you choose. **A miss:** - prints the **final score**; - puts the score back to **0** and the speed back to **the knob's speed**. .font-small[ The knob now sets the **starting** speed. If your program still reads the knob at every step, it will undo every speed-up. Where should the knob be read now? ] ] .pull-right.w48[ .done[ **Done when:** - five hits in a row print `1, 2, 3, 4, 5`, and you can **see** it get faster; - it never gets faster than your limit, however long you play; - a miss prints the final score and the next round starts slow again. ] .font-small[ **Memory check:** `score` and the speed have to survive from one press to the next. Where do variables like that live? *(Class 20: outside every function.)* ] ] --- class: small-font # Bug hunt: does every press count? .pull-left.w48[ Turn the knob to the **slowest** speed. Then try each of these **five times**, on the target: 1. **Press and hold** until the light moves on. 2. **A quick tap**, in and out, as fast as you can. 3. A tap right **as the target lights up**. 4. A tap right **before it moves on**. Count how many of each were heard. ] .pull-right.w48[ **In your notebook:** - Which kinds of press were **missed**? - At what moment does your program actually **look** at the button? Find that line. - What is the board doing **the rest of the time**? .emphasis[ **Don't fix it today.** Describe it exactly. Fixing it is all of Class 24, and it means changing how your program waits. ] ] --- class: small-font # Sign-off, then make it yours .pull-left.w50[ **Sign-off with Dr. Alvear: 1,000 points** | Mission | Show | Points | |---|---|---| | 4 | start-up sound, one `pressed` per press | 200 | | 5 | hit and miss, each with its sound | 400 | | 6 | score, speed-up with a limit, reset on a miss | 400 | Bring your **bug hunt** notes: which presses are missed, and why. ] .pull-right.w46[ **Finished early? Pick one.** - **A different note for every LED**, low on the left, high on the right. - **A victory tune** at score 10. Keep its notes in an **array**. - **Show the score** on the LEDs after a miss: blink the target once per point. - **Near miss:** pressing on LED 2 or 4 gets its own sound, and doesn't cost as much. ] --- class: small-font # Stuck? .pull-left.w48[ | What you see | Usual cause | |---|---| | No sound at all | speaker on the wrong pin, or `tone()` names a different pin | | A sound that never stops | `tone()` without a time. Add one, or `noTone()` | | Second note cuts off the first | no `delay()` between them | | One press counts many times | no `wasPressed`, or it isn't updated **every** trip | | Every press is a miss | comparing `i == 10`: the target is **index** 2 | ] .pull-right.w48[ | What you see | Usual cause | |---|---| | Button always pressed | legs on the same side are always connected. Use **diagonal** legs | | Score is always 1 | `int score = 0;` is **inside** a function | | Never speeds up | you still set the speed from the knob at every step | | Speeds up, then the light stops | no limit: the time went to 0 or below | | Some presses ignored | not today's problem: write it in the bug hunt | ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - Your **hit** and **miss** sounds: which notes, how long, and why they sound right. - How much faster after each hit, your **limit**, and why. - **The bug hunt:** which presses are missed, the line where your program looks at the button, and what the board is doing the rest of the time. - A guess: how could a program wait for the next LED **and** keep watching the button at the same time? ] .center[ **Next class:** the bug gets fixed, and the game gets lives and a high score. **Leave everything wired.** ]