class: center, middle, inverse, title-slide .title[ # Stop the Light: You Write the Code ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### Appendix — Stop the Light, part 1 of 3 (planned for Class 22) ] --- <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; } .leds { font-size: 44px; letter-spacing: 14px; text-align: center; margin: 10px 0 0 0; } </style> # Learning Targets .lt-box[ - Write a program from an empty file, starting from a plain-English description. - Use an **array** to hold a list of pins, and a **`for` loop** to walk through it, forwards and backwards. - Read a voltage with **`analogRead()`**, and turn the reading into a number you can use with **`map()`**. ] .eu-label[Essential Understanding:] For the dispenser, you adapted a program someone handed you. From today, the file starts empty, and every line in it is one you chose. The trick is never to write the whole thing at once: describe it in plain English, build the smallest piece that works, and test it before adding the next. --- # Agenda .agenda-box[ 1. The new project: **Stop the Light** 2. Wire it: five LEDs and a knob 3. .tool[Tool] Turn an LED on and off 4. .mission[Mission 1] Test your wiring 5. .tool[Tools] Arrays and `for` loops 6. .mission[Mission 2] The bouncing light 7. .tool[Tools] `analogRead()` and `map()` 8. .mission[Mission 3] The knob sets the speed 9. Sign-off with Dr. Alvear, then wrap-up ] .center[ **No code to copy today.** The tool slides show examples that do something *else*. You write the game. ] --- class: small-font # The new project: Stop the Light .leds[ 🔴 🔴 🟢 🔴 🔴 ] .center[ A light runs back and forth along five LEDs. Press the button **exactly** when the green one is lit.<br>Hit it and the light speeds up. Miss, and you lose a life. ] | Class | Missions | The new tool | Points | |---|---|---|---| | **22 (today)** | The light bounces, and a knob sets its speed | arrays, `for`, `analogRead()`, `map()` | 1,000 | | **23** | It becomes a game: a button, sounds, a score | `tone()`, and checking *which* LED is lit | 1,000 | | **24** | It never misses a tap. Lives, game over, high score. Then play each other's games | `millis()` in place of `delay()` | 1,000 | .font-small.center[ **3,000 points in all.** Each class's points come from its **sign-off**: show Dr. Alvear the missions working before you leave. ] --- class: small-font # This time, you write it .pull-left.w48[ **What's different from the dispenser** - `main.cpp` starts **empty**. Nothing to copy. - Each new tool comes with an example that is **not** this game. Your job is to adapt it. - Each mission has a **"done when"** test. It isn't done until the test passes. - Your group decides how the code looks. There is more than one right answer. ] .pull-right.w48[ **How to not get stuck** 1. Say what you want in **plain English** first, as a comment. 2. Write the **smallest** piece that does something. 3. **Upload and test.** Then add the next piece. ] --- class: small-font # Wire it: five LEDs and a knob .pull-left.w52[ <img src="assets/schematics/stop-light-leds-knob.svg" alt="Arduino Uno: pins 8 to 12 each through a 470 ohm resistor and an LED to ground, the middle LED on pin 10 marked as the target; a 10 kilohm potentiometer across 5V and GND with its wiper on A0" style="width:100%;max-height:400px;"/> ] .pull-right.w44[ 1. **Unplug the board.** Run the board's **GND** to the breadboard's **blue rail**. 2. Five LEDs in a row: **pin 8 → 470 Ω → LED → GND rail**, then pins 9, 10, 11, 12. Long leg toward the resistor. 3. The middle one, **pin 10**, is the **target**: give it a different colour. 4. **The knob (10 kΩ pot):** one outer leg to **5V**, the other outer leg to **GND**, the **middle** leg to **A0**. 5. In PlatformIO, make a **new project** called `stoplight` (board **Arduino Uno**, framework **Arduino**). .font-small[ The knob is the **Class 6 voltage divider**. Today the board measures the middle leg instead of your multimeter. ] ] --- class: small-font # .tool[Tool] Turn an LED on and off .pull-left.w48.code-tight[ ```cpp #include <Arduino.h> void setup() { pinMode(8, OUTPUT); // pin 8 drives something } void loop() { digitalWrite(8, HIGH); // 5 V on pin 8: LED on delay(1000); // wait 1000 ms = 1 s digitalWrite(8, LOW); // 0 V on pin 8: LED off delay(250); // wait a quarter second } ``` ] .pull-right.w48[ Three functions do everything on this slide: | Line | What it does | |---|---| | `pinMode(8, OUTPUT);` | pin 8 will **send** a voltage, not read one. Once, in `setup()`. | | `digitalWrite(8, HIGH);` | puts **5 V** on pin 8 | | `digitalWrite(8, LOW);` | puts **0 V** on pin 8 | | `delay(1000);` | the board **waits**, doing nothing, for 1000 ms | `setup()` runs **once** when the board starts. `loop()` runs **over and over**, forever. .font-small[ This one stays on for a second and goes off for a quarter. Change the numbers and upload to see the difference. ] ] --- class: small-font # .mission[Mission 1] Test your wiring .pull-left.w44.code-tight[ Start from this, and nothing else: ```cpp #include <Arduino.h> void setup() { } void loop() { } ``` ] .pull-right.w52[ Write a program that lights **LED 1, then 2, 3, 4, 5**, one at a time, half a second each, and repeats. Everything you need is on the last slide: `pinMode`, `digitalWrite` and `delay`, once for each LED. .done[ **Done when:** each LED lights alone, in order, left to right. If one stays dark, is it the **code** or the **wiring**? Swap that LED's pin number with a working one's and see if the problem moves. ] .font-small[ Yes, it's long. Count how many lines you wrote. The next two tools make it shorter. ] ] --- class: small-font # .tool[Tool] Arrays: one name, a list of values .pull-left.w48.code-tight[ ```cpp int temps[] = {68, 71, 75, 73, 70}; void setup() { Serial.begin(9600); Serial.println(temps[0]); // 68 Serial.println(temps[2]); // 75 Serial.println(temps[4]); // 70 temps[1] = 80; // change one Serial.println(temps[1]); // 80 } ``` ] .pull-right.w48[ An **array** keeps a list under one name. Each value has a numbered slot, its **index**, in square brackets. | Index | 0 | 1 | 2 | 3 | 4 | |---|---|---|---|---|---| | `temps[...]` | 68 | 71 | 75 | 73 | 70 | .emphasis[ **Counting starts at 0.** Five values live in slots **0 to 4**. There is no `temps[5]`, and the board won't warn you: it reads whatever is in memory next door. ] An array can hold anything that is a number. **Pin numbers are numbers.** ] --- class: small-font # .tool[Tool] `for`: do something for each one .pull-left.w50.code-tight[ ```cpp // up: 0, 1, 2, 3, 4 for (int i = 0; i < 5; i++) { Serial.println(temps[i]); } // down: 10, 9, 8 ... 1, then liftoff for (int n = 10; n >= 1; n--) { Serial.println(n); delay(1000); } Serial.println("Liftoff!"); ``` ] .pull-right.w46[ A `for` loop has three parts, separated by `;`: | Part | Above | Means | |---|---|---| | start | `int i = 0` | begin at 0 | | keep going while | `i < 5` | stop when this is false | | each step | `i++` | add 1 (`n--` takes 1 away) | Everything between `{` and `}` runs **once for each value**. .emphasis[ **Arrays and `for` loops go together.** `temps[i]` with `i` going 0 to 4 visits every slot. Change `i < 5` to `i <= 5` and you visit a slot that doesn't exist. ] ] --- class: small-font # .mission[Mission 2] The bouncing light .pull-left.w48[ Make the light run **left to right, then back, right to left**, forever, like a scanner. **Start from Mission 1.** Look at your code: what changes from one LED to the next? Only the pin number. That's your **array**, and the slot number is your **`i`**. Write the plan as comments first: ```cpp // light LED i, wait, turn it off // do that for i = 0 to 4 // then come back ``` ] .pull-right.w48[ .done[ **Done when:** - the light goes **1 2 3 4 5 4 3 2 1 2 3...** smoothly, forever; - your pin numbers are written **once**, in an array; - your `setup()` uses a `for` loop for the five `pinMode`s. ] .font-small[ **Watch the ends.** Does LED 5 (or LED 1) stay lit twice as long as the others? That's because it's in both trips. Fix it by changing **where each `for` starts or stops**. ] ] --- class: small-font # .tool[Tool] `analogRead()`: how many volts? .pull-left.w48.code-tight[ ```cpp void setup() { Serial.begin(9600); } void loop() { int reading = analogRead(A0); Serial.println(reading); delay(200); } ``` ] .pull-right.w48[ `digitalRead()` only answers HIGH or LOW. **`analogRead()`** answers *how many volts*, as a number from **0 to 1023**. | Voltage on A0 | `analogRead(A0)` | |---|---| | 0 V | 0 | | 2.5 V | about 512 | | 5 V | 1023 | **Try it** in a scratch project, or for a minute in yours. Turn the knob all the way each way and watch the numbers. .font-small[ **Check it like an engineer:** put your multimeter on A0 at the same time. Volts × 204.6 should be close to the number on the screen. ] ] --- class: small-font # .tool[Tool] `map()`: turn one range into another .pull-left.w50.code-tight[ ```cpp int reading = analogRead(A0); // 0 to 1023 int percent = map(reading, 0, 1023, 0, 100); // 0 → 0, 512 → 50, 1023 → 100 int flipped = map(reading, 0, 1023, 100, 0); // 0 → 100, 1023 → 0 Serial.print(percent); Serial.println("%"); ``` ] .pull-right.w46[ `map()` slides a number from one range onto another: ```cpp map(value, fromLow, fromHigh, toLow, toHigh) ``` Swap the last two and the direction flips: knob to the right can mean **more** or **less**. .font-small[ `map()` only does **whole numbers**. It won't give you 49.8, it gives you 49. That's fine for milliseconds. ] ] --- class: small-font # .mission[Mission 3] The knob sets the speed .pull-left.w48[ Right now, how long each LED stays on is a fixed number. Make the **knob** choose it. You decide the range. Some questions to answer first, in your notebook: - What's **too slow** to be fun? What's **impossible**? - Should turning **right** mean faster or slower? - How often should the program look at the knob: once per bounce, or at every LED? Print the speed to the Serial Monitor so you can see what your knob is doing. ] .pull-right.w48[ .done[ **Done when:** - turning the knob **while it runs** changes the speed, and you can see it change; - the slowest and fastest speeds are ones **you chose**, and you can say why; - your speed is printed to the Serial Monitor. ] .font-small[ **Hint:** the knob reading goes in, a time in **milliseconds** comes out, and that number goes into your `delay()`. ] ] --- class: small-font # Sign-off, then make it yours .pull-left.w48[ **Sign-off with Dr. Alvear: 1,000 points** | Mission | Show | Points | |---|---|---| | 1 | the five LEDs light in order | 200 | | 2 | the bouncing light, with an array and `for` loops | 400 | | 3 | the knob changing the speed live, and the printed speed | 400 | ] .pull-right.w48[ **Finished early? Pick one.** - **Difficulty levels:** the knob picks a level **1 to 5** instead of a speed, and prints `Level 3`. Each level has its own speed. - **Start-up show:** before the first bounce, flash all five LEDs three times. - **A trail:** the LED behind the moving one stays on, so the light looks like it has a tail. - **Random start:** each time it begins, it starts from a random end. (`random(2)` gives 0 or 1.) ] --- class: small-font # Stuck? .pull-left.w48[ | What you see | Usual cause | |---|---| | One LED never lights | backwards LED, or its pin number isn't in your array | | A weird extra flash, or a random pin flickers | `i <= 5`: you went past the last slot | | LED 1 or LED 5 stays on twice as long | both `for` loops include the end | | All LEDs stay on | you turn them on but never `LOW` | | `expected ';'` / `expected '}'` | look at the line **before** the one it names | ] .pull-right.w48[ | What you see | Usual cause | |---|---| | Knob reads 0 or 1023 and won't move | the middle leg isn't on A0, or an outer leg isn't on 5V/GND | | Knob reading jumps around a little | normal: a few counts of noise | | Speed only changes at the end of a bounce | you read the knob once per bounce. Is that what you want? | | Turning right makes it slower and you wanted faster | swap the last two numbers in `map()` | | Serial Monitor shows nothing | `Serial.begin(9600);` in `setup()`? | ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - Your `loop()` in **plain English**, one line per idea, the way you'd explain it to someone who has never coded. - Your knob's range: **slowest and fastest** speed, and why you chose them. - One bug you hit today: what you **saw**, what you **checked**, what you **changed**. - How many lines was Mission 1? How many lines would it be with **20** LEDs, written your new way? ] .center[ **Next class:** a button and a speaker, and it becomes a game. **Leave everything wired.** ]