class: center, middle, inverse, title-slide .title[ # Project: The Automatic Dispenser ] .subtitle[ ## Programmable Electronics — Unit 3 ] .date[ ### Class 18 ] --- <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%; } .cards { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; margin-top: 8px; } .card { border: 2px solid #364F6B; border-radius: 8px; padding: 10px 16px; font-size: 21px; line-height: 1.35; } .card h3 { font-size: 24px !important; } .card h3 { margin: 0 0 4px; font-size: 21px; color: #364F6B; } </style> # Learning Targets .lt-box[ - Control a servo from code using a library. - Build a base circuit and starter program that every version of the project shares. - Choose a version of the project and draw it as **sense → decide → act**. - Spot the flaw in a program by testing it, before fixing it. ] .eu-label[Essential Understanding:] Most automatic machines are the same three blocks: something that notices, a decision, and something that moves. If you build those blocks well, the cat feeder, the cereal dispenser and the trash can are mostly the same machine with different rules. --- # Agenda .agenda-box[ 1. The project: a machine that serves things on its own 2. Four versions. Pick one. 3. **Build:** the base circuit (servo gate + button) 4. **Code:** the starter program, then find its flaw 5. Design your mechanism 6. The road to the milestone ] .center[ This project runs **from today to Class 22**, and it **replaces the traffic light** as the Unit 3 milestone. Every class from now on teaches one idea, and then you put that idea into your machine. ] --- # The project: an automatic dispenser .pull-left.w48[ A machine that **notices** something and **serves** something, with nobody touching it. <br> .emphasis-center[ **sense** → **decide** → **act** ] <br> - **Sense:** is something there? *(today a button; later an ultrasonic sensor)* - **Decide:** your code. When? How much? How often? - **Act:** a **servo** swings a gate open, then closed. ] .pull-right.w48[ **Every group builds the same base.** The servo, the gate, and the starter code are identical. **What's different is the rules.** A cat feeder shouldn't feed the cat every time it walks past. A trash can should stay open while you're standing there. Those rules are code, and you'll write them. .font-small[ This is the course's essential question again: the machine *notices* something and *responds*. ] ] --- # Four versions. Pick one. .cards[ .card[ ### 🐱 Cat feeder The cat walks up, and one portion of kibble drops. But only once per meal, or the cat would eat all day. Keeps a log of when it fed. ] .card[ ### 🥣 Cereal dispenser Put a bowl under the spout and cereal pours. No bowl, no cereal. A knob picks small, medium or large. ] .card[ ### 🍬 Trick-or-treat machine Reach in and one candy drops, with a sound. One per hand, and it counts how many it has given away. ] .card[ ### 🗑️ Touchless trash can Walk up and the lid lifts. It stays open while you're there, and closes a few seconds after you leave. ] ] .font-small.center[ Same servo, same code to start. Test with something dry and small: rice, beads, Cheerios, kibble. ] --- class: small-font # Today's build, start to finish .pull-left.w48[ **Build: the base circuit** <ol start="1"><li><strong>Arduino 5V → + rail</strong>, <strong>GND → − rail</strong>.</li><li><strong>100 µF</strong> across the rails: long leg +, short leg −.</li><li><strong>Servo:</strong> red → +, brown/black → −, signal (orange/white) → <strong>pin 9</strong>.</li><li><strong>Button:</strong> pin 7 → GND. Today it stands in for the sensor.</li></ol> **Code** <ol start="5"><li>Add the <strong>Servo</strong> library line to <code>platformio.ini</code>.</li><li>Upload the starter program. Press the button: the gate opens and closes.</li><li>Find the <strong>flaw</strong>.</li></ol> ] .pull-right.w48[ **Then** <ol start="8"><li>Pick your version.</li><li>Find your gate's <strong>open</strong> and <strong>closed</strong> angles.</li><li>Sketch the mechanism and draw your version as <strong>sense → decide → act</strong>.</li></ol> .font-small[ **You need:** one servo and its bag of horns, one **100 µF** capacitor, one pushbutton, jumper wires. One laptop, one Arduino, one USB cable per group. **Next class, bring:** an empty plastic bottle (500 mL is ideal), cardboard, tape. ] ] --- class: small-font # Build: the base circuit <img src="assets/schematics/dispenser-base.svg" alt="Arduino Uno: pin 9 to the servo's signal wire; 5V and GND to the servo's power, with a 100 microfarad capacitor across them; a button from pin 7 to GND. An ultrasonic sensor on pins 5 and 6 is drawn grey and dashed: it comes later." style="width:100%;max-height:250px;"/> .pull-left.w48[ - **Servo:** **signal → pin 9**, **red → 5V**, **brown or black → GND**. *(Signal is orange or white.)* - **100 µF** across the servo's power, **short leg to GND**. When the motor starts it gulps current; the cap covers the gulp so the board doesn't reset. ] .pull-right.w48[ - **Button:** **pin 7 → GND**, diagonally opposite legs. `INPUT_PULLUP`, so pressed = LOW. - The grey **ultrasonic sensor** comes later. Leave pins 5 and 6 free. - Use the Arduino's **5V** pin, not the 6 V battery pack. ] --- class: small-font # Code: the starter program .pull-left.w56.code-tighter[ ```cpp #include <Arduino.h> #include <Servo.h> Servo gate; // the servo that opens the gate const int CLOSED = 0; // angle that blocks the opening const int OPEN = 90; // angle that lets food fall const int PORTION = 500; // ms the gate stays open bool somethingThere() { // is a cat, a bowl, a hand there? return digitalRead(7) == LOW; // for now, a button } void dispense() { Serial.println("Dispensing!"); gate.write(OPEN); delay(PORTION); gate.write(CLOSED); delay(300); // give the gate time to close } void setup() { gate.attach(9); gate.write(CLOSED); pinMode(7, INPUT_PULLUP); Serial.begin(9600); Serial.println("Dispenser ready."); } void loop() { if (somethingThere()) { dispense(); } } ``` ] .pull-right.w40[ **First, one extra line.** Add this to the bottom of `platformio.ini`, or the build can't find `Servo.h`: ```ini lib_deps = arduino-libraries/Servo ``` **What's new:** - `#include <Servo.h>` brings in a **library**: code someone else wrote, so you don't have to make the servo's pulses yourself. - `Servo gate;` makes a servo **object**. `gate.write(90)` sends it to 90°. - `const` makes a **constant**: a name for a number that never changes. Change `OPEN` once at the top, and it changes everywhere. ] --- class: small-font # Test it, then find the flaw .pull-left.w48[ **Test.** Upload and open the **🔌 Serial Monitor**. 1. **Tap** the button. The servo swings to 90° and back, and "Dispensing!" prints once. 2. **Hold** the button down for five seconds. Count the "Dispensing!" lines. .emphasis[ **That's the flaw.** Holding the button is what a bowl sitting under a sensor, or a cat that sits in front of its feeder, will do. Right now your machine would empty itself. ] **Don't fix it yet.** Next class is about exactly this problem. Write down what happened, and why you think it happens. *(Hint: what does `loop()` do after `dispense()` ends?)* ] .pull-right.w48[ **Find your gate's angles.** Push a horn onto the servo and tape a strip of cardboard to it as a test gate. - Change `CLOSED` and `OPEN`, upload, and watch. Which angle blocks the opening? How far does it need to swing to let food out? - Change `PORTION`. What's the shortest time that still lets something fall? .font-small[ **Gate goes the wrong way?** Pull the horn off and put it back on at a different angle. That's easier than fighting the numbers. **Servo jams and hums at 0 or 180?** It's pushing against its own stop. Use 10 and 170 instead. **Board restarts every time the servo moves?** Check the 100 µF, short leg to −. ] ] --- class: small-font # Design your mechanism .pull-left.w48[ **The gate (cat, cereal, candy):** an empty bottle, **upside down**, held in a cardboard stand. A cardboard flap on the servo horn sits **under the bottle's neck** and blocks it. The servo swings the flap away, food falls, the flap swings back. - Cut the bottom off the bottle so you can fill it from the top. - The neck opening has to be **bigger than the food**. Cereal and candy may need the neck cut wider. - The flap must **slide under** the opening, not push up into it, or it jams. **The lid (trash can):** a box with a hinged cardboard lid. The servo arm pushes the lid **up** from inside, or pulls it with a string. ] .pull-right.w48[ **In your notebook, before you cut anything:** 1. **Sketch the mechanism** from the side. Label the bottle, the flap, the servo, and where the food lands. 2. Where does the **sensor** go, so it sees the cat, the bowl, or the hand, and not the falling food? 3. What **holds the servo still**? A servo that isn't fixed down moves itself instead of the gate. .emphasis[ A cardboard prototype that works beats a beautiful one that jams. ] ] --- class: small-font # The road to the milestone Each class teaches one idea on a small exercise. Then you add it to your machine. | Class | You learn | Your dispenser gets | |---|---|---| | **18** (today) | servos, libraries, constants | the base circuit, starter code, a version, a sketch | | **19** | measuring a threshold, prototyping | the **ultrasonic sensor**, **once per visit**, and the cardboard prototype | | **20** | variables that remember, `millis()` | **your rules**: no misfires, counts, cooldowns, limits | | **21** | | **final build:** five in a row with real stuff, notebook done | | **22** | | **showcase and grading** | .font-small.center[ The project sheet has the rubric and what "done" looks like for each version. ] --- class: small-font # Finished early? .pull-left.w48[ Pick any. All of them will be useful later. 1. **A light.** An LED on pin 13 that is on while the gate is open. 2. **Count.** Keep a count of portions in a variable, and print it each time: "Portion 3". 3. **Ready light.** A green LED that is on when the machine is waiting, and off while it dispenses. 4. **Two shakes.** Some food jams. Open and close the gate twice quickly for each portion. Does more come out? ] .pull-right.w48[ **Trash can groups:** `dispense()` opens and closes right away. Your lid needs to **stay open while somebody is there**. Try: open the lid when `somethingThere()` is true, and close it only when it's false. Hold the button: the lid should stay up. .emphasis[ Notice that this *is* a version of the flaw the other groups have: a machine that keeps responding as long as something is there. For the trash can it's the feature. ] ] --- class: small-font # Got it working? Add the real sensor: wiring <img src="assets/schematics/dispenser-ultrasonic.svg" alt="The base circuit plus the ultrasonic sensor: VCC to 5V, TRIG to pin 5, ECHO to pin 6, GND to ground. The pin 7 button stays as an owner button." style="width:100%;max-height:250px;"/> .pull-left.w48[ The sensor has four pins, labelled on the front. Unplug the USB first. - **VCC → + rail** (5V) - **Trig → pin 5** - **Echo → pin 6** - **GND → − rail** ] .pull-right.w48[ **Keep the button.** It becomes the **owner button**: dispense on demand, even with nothing in front of the sensor. **Point the sensor** where the cat, the bowl, or the hand will be, and *not* where the food falls. The two round "eyes" are a speaker and a microphone. ] --- class: small-font # Add the real sensor: code .pull-left.w50.code-tighter[ ```cpp // Add these near the top, under PORTION: const int TRIG = 5; const int ECHO = 6; const int NEAR = 10; // cm: closer = "something there" 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 } // Replace the old somethingThere() with this one: bool somethingThere() { long cm = readDistanceCm(); Serial.print("distance: "); Serial.println(cm); return cm < NEAR; } ``` ] .pull-right.w46.code-tighter[ ```cpp // In setup(), add: pinMode(TRIG, OUTPUT); pinMode(ECHO, INPUT); // Replace loop() with this one: void loop() { if (somethingThere() || digitalRead(7) == LOW) { dispense(); } delay(60); // the sensor needs a rest between chirps } ``` **How it works.** Pin 5 makes the sensor chirp, too high for you to hear. The echo pin stays HIGH until the chirp bounces back. `pulseIn` measures how long that took. **Why 58?** Sound travels 1 cm in about 29 µs, and the chirp goes there **and back**. ] --- class: small-font # Add the real sensor: test it, tune it .pull-left.w48[ 1. Upload and open the **🔌 Serial Monitor**. Distances should scroll. 2. Move your hand toward the sensor and away. Do the numbers make sense? Check one with a ruler. 3. Put **the real thing** where it'll go: the bowl, a stuffed cat, your hand in the candy slot. **What distance does it read?** What does it read when it's gone? 4. Set `NEAR` **between** those two numbers. .font-small[ **Always 999?** Trig and echo swapped, or the sensor isn't on 5V and GND. **Jumps around?** Soft, small, or angled things reflect badly. Try a flat piece of cardboard. ] ] .pull-right.w48[ **Write in your notebook:** the distance with and without your target, and the `NEAR` you chose. You'll need those numbers for the milestone, and for the **trash can**, `NEAR` may need to be 40 or more. .emphasis[ **The flaw is worse now.** Leave a bowl under the spout and it dispenses forever. A button you have to hold is one thing; a bowl just *sits there*. That's next class. ] ] --- class: center, middle # Wrap-up — in your notebook .hw-box[ - **Your version** (cat, cereal, candy, or trash) and its rules in one sentence: *when* does it act, and *how much*? - Draw it as three blocks: **sense → decide → act**. Label the pins. - **The flaw:** what happened when you held the button, and *why*? Use the word `loop()`. - Your gate's **open** and **closed** angles, and the **portion** time that worked. - **Bring next class:** an empty plastic bottle, cardboard, tape. ]