class: center, middle, inverse, title-slide .title[ # Dispenser: Teaching the Machine Rules ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### Class 20 ] --- <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%; } .tool { display: inline-block; background: #364F6B; color: #fff; border-radius: 6px; padding: 1px 10px; font-weight: 700; font-size: 0.85em; } .flow { font-family: 'Source Code Pro', monospace; font-size: 19px; background: #EAF1F8; border-radius: 8px; padding: 12px 16px; text-align: center; line-height: 1.6; } </style> # Learning Targets .lt-box[ - Read the dispenser program and explain what every part does. - Explain why the program can't follow a rule unless it **remembers** something. - Use five tools: a **counter**, the **last reading**, a **streak**, the **clock** (`millis()`), and a **count in a time window**. - Turn the rules you wrote last class into code, and test each one. ] .eu-label[Essential Understanding:] `loop()` lives only in the present: it sees what the sensor sees *right now*. Every rule about the past ("once per visit", "not again so soon", "that's the third one") needs a variable that remembers. Choosing what to remember **is** designing the machine. --- # Agenda .agenda-box[ 1. **Read the program**, top to bottom 2. **Trace it:** how it knows to give only one 3. **The toolbox:** five ways to remember 4. Which tools does **your** machine need? 5. **Build your rules** in the template, one at a time, each with its test ] .center[ Today you get **tools**, not answers. Every example on these slides does something *different* from your dispenser. Your job is to adapt them. ] --- class: small-font # Read the program: sense and act .pull-left.w54.code-tighter[ ```cpp 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: nothing near return us / 58; // µs → cm } bool somethingThere() { long cm = readDistanceCm(); Serial.print("distance: "); Serial.println(cm); return cm < NEAR; } void dispense() { Serial.println("Dispensing!"); openGate(); delay(PORTION); closeGate(); delay(300); } ``` ] .pull-right.w42[ **`readDistanceCm()`** answers *"how far?"* with a number. It chirps, then `pulseIn` times how long the echo pin stays HIGH. Sound goes there **and back**, about 58 µs per cm. No echo within 30 ms? It answers 999: "nothing near." **`somethingThere()`** answers *"is something there?"* with **true** or **false**. It's the whole sensor, boiled down to one yes or no. Swap the sensor and only this function changes. **`dispense()`** is the **act**: one portion. Open, wait, close. .font-small[ In the template, `openGate()` and `closeGate()` are their own functions. The trash can needs them apart: open now, close *later*. ] ] --- class: small-font # Read the program: loop and decide .pull-left.w50.code-tight[ ```cpp void decide(bool there) { if (there && !wasThere) { dispense(); } wasThere = there; } void loop() { bool there = somethingThere() || ownerPressed(); decide(there); delay(60); } ``` ] .pull-right.w46[ **`loop()`** asks one question, "is something there?", and hands the answer to **`decide()`**. Then it rests 60 ms and does it all again, **about 15 times a second**, forever. **`decide()`** is where the rules live. Right now there's one rule: *if something **just arrived**, dispense.* `wasThere` is how it knows. That's the next slide. `||` means **or**: the owner button counts as "something there". ] <br> .emphasis-center[ **sense** = `somethingThere()` → **decide** = `decide()` → **act** = `dispense()` ] --- class: small-font # Trace it: how does it know to give only one? A hand arrives and stays. Fill in the **?** cells, one row per trip through `loop()`: | Trip | Time | Distance | `there` | `wasThere` (before) | What `decide()` does | |---|---|---|---|---|---| | 1 | 0.00 s | 999 | false | false | nothing | | 2 | 0.09 s | 6 | **true** | false | dispense *(takes 0.8 s)* | | 3 | 0.95 s | 6 | **true** | **true** | ? | | 4 | 1.01 s | 6 | **true** | ? | ? | | 5 | 1.07 s | 999 | false | ? | ? | `there` is the same in trips 2, 3 and 4. The only thing that tells them apart is **`wasThere`**: a variable that remembers the last trip. Delete it, and trips 3 and 4 dispense too. That was the Class 18 flaw. .emphasis[ **`loop()` has no memory of its own.** Every rule about the past ("once per visit", "not again so soon", "that's the third one") needs a variable like `wasThere`. That's the whole toolbox. ] --- class: small-font # Where memory lives .pull-left.w48.code-tight[ ```cpp int count = 0; // ✅ MEMORY: up here, // outside every function void decide(bool there) { int oops = 0; // ❌ born every trip, // forgotten at the } count++; oops++; Serial.println(count); // 1, 2, 3, 4... Serial.println(oops); // 1, 1, 1, 1... } ``` ] .pull-right.w48[ A variable made **inside** a function is new every time the function runs. When it reaches its closing `}`, the variable is gone. A variable made **outside** every function, near the top, lives as long as the board has power. **In the template, these go in the `MEMORY` section.** .font-small[ | Type | Holds | Use it for | |---|---|---| | `int` | whole numbers up to 32,767 | counts, streaks | | `bool` | true or false | "was it there?", "is the lid open?" | | `unsigned long` | up to 4 billion | **anything holding `millis()`** | ] ] --- class: small-font # .tool[Tool 1] A counter .pull-left.w50.code-tight[ ```cpp int visits = 0; void decide(bool there) { if (there) { visits++; // add 1 Serial.print("Visits: "); Serial.println(visits); } } ``` ] .pull-right.w46[ `visits++` is short for `visits = visits + 1`. **Try it.** Stand in front of the sensor for three seconds. What does it count? Is that "visits"? .emphasis[ It counts **loop trips**, about 15 a second, not visits: the Class 18 flaw again. To count visits, put the `++` **inside** the "just arrived" `if`, next to `dispense()`. ] **Use it for:** a log of portions, candies given away, lid openings, an "empty, refill me" warning after N. ] --- class: small-font # .tool[Tool 2] The last reading (you already have it) .pull-left.w50.code-tight[ ```cpp // in MEMORY already: bool wasThere = false; void decide(bool there) { if (there && !wasThere) { Serial.println("Hello!"); // just arrived } if (!there && wasThere) { Serial.println("Bye!"); // just left } wasThere = there; // remember, for next trip } ``` `&&` is **and**. `!` is **not**. ] .pull-right.w46[ Compare **now** with **last trip**: | `wasThere` | `there` | What happened | |---|---|---| | false | false | still nobody | | false | **true** | **it just arrived** | | true | true | it's still here | | **true** | false | **it just left** | The last line of `decide()` saves today's reading so the next trip can compare. **Forget that line and nothing works.** **Your dispenser already uses the "just arrived" row:** that's one portion per visit. The **"just left"** row is new: the trash can needs it. ] --- class: small-font # .tool[Tool 3] A streak: don't believe one reading .pull-left.w50.code-tight[ ```cpp const int CONFIRM = 3; int streak = 0; void decide(bool there) { if (there) { if (streak < CONFIRM) streak++; } else { streak = 0; // one miss: start over } bool sure = (streak == CONFIRM); if (sure) { Serial.println("Yes, really there."); } } ``` ] .pull-right.w46[ The sensor **misfires**: now and then one reading says 4 cm when nothing is there. A falling Cheerio can do it too. One bad reading shouldn't cost a portion. So count **readings in a row**. One glitch makes `streak` 1, and the next good reading sends it back to 0. Only something that's *really* there reaches `CONFIRM`. .font-small[ **The price:** the machine reacts a little later, about 0.07 s per count. A bowl can wait (`CONFIRM` = 10). A hand might not. ] .emphasis[ `sure` is a **better `there`**. Anywhere you used `there`, you can use `sure` instead. ] ] --- class: small-font # .tool[Tool 4] The clock: how long since? .pull-left.w50.code-tight[ ```cpp unsigned long lastHello = 0; void decide(bool there) { if (there && millis() - lastHello >= 10000) { Serial.println("Hello! Not again for 10 s."); lastHello = millis(); // remember WHEN } } ``` ] .pull-right.w46[ `millis()` is a stopwatch that started when the board powered on: the number of **milliseconds** since then. Two moves, always together: 1. **Write down when:** `lastHello = millis();` 2. **Ask how long since:** `millis() - lastHello` Then compare it to a time. `>= 10000` means "at least 10 seconds ago." .font-small[ **Always `unsigned long`** for times. An `int` tops out at 32,767 ms, about 33 seconds, and then goes negative. Unlike `delay()`, nothing waits here. The machine keeps watching the whole time. ] ] --- class: small-font # .tool[Tool 5] No more than N in a while .pull-left.w54.code-tighter[ ```cpp const int MAX = 3; const unsigned long WINDOW = 60000; // 1 minute int inWindow = 0; unsigned long windowStart = 0; // wasThere: already in MEMORY void decide(bool there) { if (millis() - windowStart >= WINDOW) { inWindow = 0; // window's over: start fresh } if (there && !wasThere) { // Tool 2: someone arrived if (inWindow < MAX) { if (inWindow == 0) windowStart = millis(); // start the clock inWindow++; Serial.println("Welcome!"); } else { Serial.println("Full. Try again later."); } } wasThere = there; } ``` ] .pull-right.w42[ This one is **Tools 1, 2 and 4 together**: a counter, that only counts arrivals, that empties itself when the clock runs out. Read it like a sentence: *"When someone arrives, welcome them, unless 3 people already came in this minute."* **Try it:** what changes if you delete `if (inWindow == 0)` and start the clock on *every* welcome? .font-small[ The minute starts at the **first** welcome, not when the board turns on. ] ] --- class: small-font # Combining tools: a pipeline Each tool takes the answer from the one before and makes it smarter. .flow[ sensor → `there` → .tool[3] streak → `sure` → .tool[2] just arrived? → .tool[4] .tool[5] allowed yet? → **act** → .tool[1] count it ] .pull-left.w48[ - Tool 3 goes **first**: clean up the reading before anything else trusts it. - Tool 2 then uses **`sure`** in place of `there`, and saves `wasThere = sure;`. - Tools 4 and 5 go **inside** the "just arrived" `if`: they decide *whether* this arrival gets served. - Tool 1 goes right **after** the act. ] .pull-right.w48[ .emphasis[ **Add one tool at a time.** Upload, run its test, and only then add the next. If you add three and it breaks, you won't know which one broke it. ] ] --- class: small-font # Which tools does your machine need? | Version | Rule | Tool | |---|---|---| | 🐱 **Cat feeder** | one portion per visit | 2 ✅ already working | | | a cat, not a misfire | 3 | | | not again until the cooldown is over (30 s stands in for 4 hours) | 4 | | | a log: "Meal 3 at 84 s" | 1 | | 🥣 **Cereal** | only when a **bowl** is there, not a passing hand | 3 | | | once per bowl | 2 ✅ already working | | 🍬 **Trick-or-treat** | one candy per hand, and not to a misfire | 2 ✅ + 3 | | | no more than 3 in 2 minutes | 5 | | | count candies given | 1 | | 🗑️ **Trash can** | open when someone arrives, **stay open** while they're there | 2 (or a `lidOpen` bool) | | | close a few seconds **after they leave** | 4 | | | count openings | 1 | .font-small.center[ Your own rules from last class count too. Find the tool that fits each one. ] --- class: small-font # The template: where your rules go .pull-left.w48[ Copy the template from **[here](code/dispenser-rules.cpp)** instead of typing, and paste it over everything in `src/main.cpp`. Then copy **your** `CLOSED`, `OPEN`, `PORTION` and `NEAR` back in. It's the program you already have, cut into labelled parts: | Part | Change it? | |---|---| | SETTINGS | your numbers, yes | | **MEMORY** | **yes: your variables go here** | | SENSE | no | | ACT | no | | **DECIDE** | **yes: your rules go here** | | SETUP, LOOP | no | ] .pull-right.w48[ **Upload it before you change anything.** It should behave exactly like last class: one portion per visit. Now you know any new bug is yours. **Then, for each rule:** 1. Read your test from last class. *"Hold a hand there 10 s. Expect: one candy."* 2. Add **one** tool to `MEMORY` and `DECIDE`. 3. Upload. Run the test. Write the result in your notebook. 4. Passed? Next rule. Failed? Next slide. ] --- class: small-font # When a rule doesn't work .pull-left.w48[ **Print your memory.** At the end of `decide()`, print every variable you added, on one line: ```cpp Serial.print(there); Serial.print(" streak="); Serial.print(streak); Serial.print(" wasThere="); Serial.println(wasThere); ``` Then watch it think. Turn the `distance:` lines in `somethingThere()` into comments so you can read it. ] .pull-right.w48[ | What you see | Usual cause | |---|---| | Count stuck at 1 | variable made **inside** `decide()` | | Still dispenses a pile | forgot `wasThere = there;` at the end | | A rule fires every time | `=` (sets) where you meant `==` (compares), inside an `if` | | Time rule works, then goes crazy after ~33 s | an `int` holding `millis()` | | Won't serve for the first 30 s after upload | `lastTime` starts at 0. Is that what you want? | | Owner button ignored | your streak or edge is eating it. Is that a rule you want? | ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - For each rule you built: the **tool(s)** you used, the **variables** you added, and the **test result**. - **What's left** for your machine before the showcase, and **who** in your group does each piece next class. - One rule that **didn't** work the first time: what you saw, what you printed to find out why, what you changed. - In one sentence: why can't `loop()` follow "once per visit" without a variable outside it? ] .center[ **Next class:** final build. **Class 22:** showcase and grading. ]