class: center, middle, inverse, title-slide .title[ # Parking Sensor: You Write the Code ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### 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; } .zones { display: flex; text-align: center; font-weight: 700; margin: 6px 0 4px 0; } .zones div { flex: 1; padding: 10px 4px; color: #fff; } .zones .z-red { background: #B5452B; border-radius: 6px 0 0 6px; } .zones .z-yellow { background: #D9A400; } .zones .z-green { background: #3D8B5F; } .zones .z-off { background: #9AA3AD; border-radius: 0 6px 6px 0; } .zones span { display: block; font-weight: 400; font-size: 0.8em; } </style> # Learning Targets .lt-box[ - Turn a sensor reading into one of several actions with **`if` / `else if` / `else`**. - Make sounds of a chosen pitch and length with **`tone()`**, and change how often they repeat. - Turn one range of numbers into another with **`map()`**, and keep it in bounds with **`constrain()`**. ] .eu-label[Essential Understanding:] A car's parking sensor is the whole course in one small machine: it **notices** a distance, **decides** which zone that is, and **responds** with a light and a sound. The noticing and the responding are wires. The deciding is a few lines of code, and today you write them from an empty file. --- # Agenda .agenda-box[ 1. The project: **a parking sensor** 2. Wire it: the sensor, three LEDs, a speaker 3. .tool[Tool] The distance sensor 4. .mission[Mission 1] See the distance 5. .tool[Tool] `if` / `else if` / `else` 6. .mission[Mission 2] The lights 7. .tool[Tools] `tone()`, `map()` and `constrain()` 8. .mission[Mission 3] The beeper 9. Sign-off with Dr. Alvear, then wrap-up ] .center[ **No game code to copy today.** The tool slides show examples that do something *else*. You write the parking sensor. ] --- class: small-font # The project: a parking sensor .pull-left.w52[ Back a car toward a wall and it starts to beep. The closer you get, the faster it beeps, until it's one solid tone: **stop**. Yours does the same thing, with a hand or a book as the wall: .zones[ <div class="z-red">RED<span>solid tone</span></div> <div class="z-yellow">YELLOW<span>fast beeps</span></div> <div class="z-green">GREEN<span>slow beeps</span></div> <div class="z-off">nothing<span>quiet, all off</span></div> ] .font-small[ ⟵ closer to the sensor · farther away ⟶ ] **You choose** where each zone starts. A real car uses about 150 cm, 60 cm and 30 cm. ] .pull-right.w44[ | Mission | What it does | Points | |---|---|---| | **1** | the distance on the screen, checked with a ruler | 200 | | **2** | the right light for each zone | 400 | | **3** | beeps that speed up, then a solid tone | 400 | .font-small.center[ **1,000 points**, from your **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**, except for one function you already know. - Each new tool comes with an example that is **not** a parking sensor. 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: the sensor, three LEDs, a speaker .pull-left.w56[ <img src="assets/schematics/parking-sensor.svg" alt="Arduino Uno: ultrasonic sensor VCC to 5V, TRIG to pin 5, ECHO to pin 6, GND to GND; pins 10, 9 and 8 each through a 470 ohm resistor to a red, yellow and green LED and then ground; pin 7 through a 220 ohm and a 100 ohm resistor to a speaker and then ground" style="width:100%;max-height:420px;"/> ] .pull-right.w40[ 1. **Unplug the board.** Board **GND** to the breadboard's **blue rail**. 2. **The sensor**, as on the dispenser: **VCC → 5V**, **TRIG → pin 5**, **ECHO → pin 6**, **GND → GND**. Put it at the **edge of the table**, facing out: that's the bumper. 3. **Three LEDs:** **pin 8 → 470 Ω → green LED → GND**, then **pin 9** yellow, **pin 10** red. No yellow? Any colour works. 4. **The speaker:** **pin 7 → 220 Ω → 100 Ω → speaker → GND**. 5. New PlatformIO project called `parking` (board **Arduino Uno**, framework **Arduino**). .font-small[ **Why two resistors?** 5 V ÷ 320 Ω ≈ 15 mA, under the 20 mA a pin should give. ] ] --- class: small-font # .tool[Tool] The distance sensor .pull-left.w52.code-tight[ ```cpp const int TRIG = 5; const int ECHO = 6; // How far is the nearest thing, in cm? // 999 means no echo: nothing in range. long readDistanceCm() { digitalWrite(TRIG, HIGH); // a 10 µs chirp delayMicroseconds(10); digitalWrite(TRIG, LOW); long us = pulseIn(ECHO, HIGH, 30000); // wait for the echo if (us == 0) return 999; // no echo return us / 58; // µs → cm } ``` .font-small[ Copy it from [here](code/read-distance.cpp) instead of typing. It goes **above** `setup()`. ] ] .pull-right.w44[ The dispenser's sensor function, unchanged. You already know what it does: 1. a short **chirp** of sound you can't hear; 2. **time** how long the echo takes to come back; 3. turn microseconds into **centimetres**. Calling it gives you a number: ```cpp long cm = readDistanceCm(); ``` .emphasis[ The sensor needs two lines in `setup()`: TRIG is an **OUTPUT** (it sends the chirp), ECHO is an **INPUT** (it listens). ] ] --- class: small-font # .mission[Mission 1] See the distance .pull-left.w44.code-tight[ Start from this, plus the sensor function: ```cpp #include <Arduino.h> // the sensor function goes here void setup() { } void loop() { } ``` ] .pull-right.w52[ Print the distance to the **Serial Monitor**, about **ten times a second**. You need: `Serial.begin(9600);`, the two `pinMode`s, `readDistanceCm()`, `Serial.println()` and a `delay()`. .done[ **Done when:** - distances scroll by on the Serial Monitor; - you hold a **book** at **10, 30 and 60 cm** on a ruler, and the screen agrees to within **2 cm**; - you wrote down what it prints with **nothing** in front, and what it prints when the book **touches** the sensor. ] .font-small[ A flat, hard book reflects sound well. A sweater or a hand at an angle doesn't. Try both. ] ] --- class: small-font # .tool[Tool] `if` / `else if` / `else`: pick one .pull-left.w48.code-tight[ ```cpp int temp = 72; // degrees F if (temp < 32) { Serial.println("freezing"); } else if (temp < 60) { Serial.println("cold"); } else if (temp < 80) { Serial.println("nice"); } else { Serial.println("hot"); } ``` ] .pull-right.w48[ The board checks the tests **top to bottom**. The **first** one that's true runs, and the rest are **skipped**. Exactly one message prints. | `temp` | prints | |---|---| | 20 | freezing | | 45 | cold | | 72 | nice | | 95 | hot (nothing else was true) | .emphasis[ **Order matters.** Put `temp < 80` first and 20° prints "nice": it *is* under 80, so the check stops there. ] .font-small[ Name your numbers at the top, like `const int COLD = 60;`. Changing a zone is then one edit. ] ] --- class: small-font # .mission[Mission 2] The lights .pull-left.w48[ Light **one** LED for the zone the book is in: | Book is... | Light | |---|---| | farther than your "nothing" distance | none | | in the far zone | green | | in the middle zone | yellow | | closer than your "stop" distance | red | **Decide first**, in your notebook: the three distances where the zones change. Write them as `const`s at the top. ] .pull-right.w48[ .done[ **Done when:** - move the book slowly in from a metre away: **off → green → yellow → red**, never two lights at once; - move it back out: the same in reverse; - each light changes within **3 cm** of the distance you chose, and the Serial Monitor shows it; - with **nothing** in front, all three are off. ] .font-small[ **Hint:** one `if` / `else if` / `else` with four branches. Each branch sets **all three** LEDs, not just the one that turns on. ] ] --- class: small-font # .tool[Tool] `tone()`: make a sound .pull-left.w48.code-tight[ ```cpp const int SPEAKER = 7; void setup() { // a doorbell: two notes tone(SPEAKER, 659, 300); // E, 300 ms delay(350); tone(SPEAKER, 523, 600); // C, 600 ms delay(1000); // an alarm: on until you stop it tone(SPEAKER, 1000); delay(2000); noTone(SPEAKER); } void loop() { // a metronome: tick, then silence tone(SPEAKER, 1200, 30); delay(500); } ``` ] .pull-right.w48[ `tone(pin, pitch, ms)` plays a note: **pitch** in Hz (vibrations per second), for **ms** milliseconds. `tone(pin, pitch)` with **no time** plays **forever**, until `noTone(pin)`. .emphasis[ **`tone()` doesn't wait.** It starts the sound and the program moves on right away. The `delay()` after it is what you hear as the gap. ] **The metronome** ticks every 500 ms: 120 a minute. Change the `500` and it speeds up or slows down. **That number is the whole trick for Mission 3.** .font-small[ Higher pitch = higher note. 200 Hz is a hum, 1000 Hz a beep, 4000 Hz a squeal. ] ] --- class: small-font # .tool[Tool] `map()` and `constrain()` .pull-left.w50.code-tight[ ```cpp int temp = 75; // degrees F // a fan: 60° → 0%, 90° → 100% int fan = map(temp, 60, 90, 0, 100); // 75° → 50% // a heater: the other way round int heat = map(temp, 60, 90, 100, 0); // 75° → 50%, 65° → 84% // 50° gives a fan of -33%. Clamp it: fan = constrain(fan, 0, 100); // now anything below 0 becomes 0, // anything above 100 becomes 100 ``` ] .pull-right.w46[ `map()` slides a number from one range onto another: ```cpp map(value, fromLow, fromHigh, toLow, toHigh) ``` **Swap the last two** and it runs backwards: more in, less out. `map()` doesn't stop at the ends of the range: give it a value **outside** and you get an answer **outside**. `constrain()` keeps it in bounds: ```cpp constrain(value, lowest, highest) ``` .font-small[ Whole numbers only: no 49.8, just 49. Fine for milliseconds. ] ] --- class: small-font # .mission[Mission 3] The beeper .pull-left.w48[ Add sound, like a real car: - **nothing** there: silent; - **green and yellow**: a short beep, then a pause. The **closer**, the **shorter the pause**; - **red**: one **solid** tone. Questions to settle first, in your notebook: - What's the **longest** pause (at the far edge)? The **shortest** (just before red)? - Closer means a **shorter** pause. Which way round do the last two numbers in `map()` go? ] .pull-right.w48[ .done[ **Done when:** - move the book in slowly: the beeps **speed up smoothly**, not in two or three jumps; - red is **one solid tone**; - pull the book away from red: the tone **stops**, and it goes back to beeping; - with nothing in front, it's **silent**; - your lights from Mission 2 still work. ] .font-small[ **Hint:** the distance goes in, a pause in **milliseconds** comes out, and that number goes into the `delay()` after your beep, just like the metronome's `500`. ] ] --- class: small-font # Sign-off, then make it yours .pull-left.w48[ **Sign-off with Dr. Alvear: 1,000 points** | Mission | Show | Points | |---|---|---| | 1 | distances on screen, matching the ruler | 200 | | 2 | off → green → yellow → red and back, one at a time | 400 | | 3 | beeps that speed up smoothly, a solid tone in red, silence when clear | 400 | ] .pull-right.w48[ **Finished early? Pick one.** - **The bar:** six LEDs (2 green, 2 yellow, 2 red). The closer, the **more** of them light, like a car's dashboard. Pins in an array, `int bar[] = {8, 9, 10, 11, 12, 13};`, and a `for` loop to light the first few. - **No flicker:** at the edge of a zone the light can flip back and forth. Change zones only after **3 readings in a row** agree (the dispenser's streak). - **Parked:** if the distance hasn't changed by more than 2 cm for **5 seconds**, go quiet. You've stopped; the car would too. (`millis()`, the dispenser's clock.) - **Your own sound:** the pitch rises as you get closer, or a two-note beep. ] --- class: small-font # Stuck? .pull-left.w48[ | What you see | Usual cause | |---|---| | Always 999 | TRIG and ECHO swapped, VCC not on 5V, or nothing hard in front | | 0, 1 or 2 cm, or wild jumps, very close | the sensor can't see closer than about 3 cm | | Two LEDs on at once | a branch turns one LED on but doesn't turn the others **off** | | Wrong colour at a distance | the order of your `if`s, or `<` where you meant `>` | | Light flickers at the edge of a zone | normal: the reading wobbles by a cm. See "No flicker" | | `expected ';'` / `expected '}'` | look at the line **before** the one it names | ] .pull-right.w48[ | What you see | Usual cause | |---|---| | No sound at all | speaker on the wrong pin, or `tone()` names a different pin | | Beeps sound like one long tone | the pause is shorter than the beep | | Beeps **slow down** as you get closer | swap the last two numbers in `map()` | | Red tone never stops | `tone()` with no time, and no `noTone()` when you leave red | | Weird pauses near the edges | the distance is outside your `map()` range: `constrain()` it | | It reacts late when you move fast | it can't look while it's inside a `delay()` | ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - Your three zone distances, and **why** you chose them. - Your `loop()` in **plain English**, one line per idea. - From far away, move the book in **fast**. How long until the beeps notice? Find the longest `delay()` in your `loop()`: what is the board doing during it? - One bug you hit today: what you **saw**, what you **checked**, what you **changed**. ]