Grabbing candy bowl on an Arduino Uno
An HC-SR04 watches across the top of a candy bowl: when a hand reaches in, a piezo cackles and a servo swings a rubber hand down to grab it. The whole build, an Arduino Uno and 3 more parts, runs here in your browser on the firmware below; open it in the editor to change the wiring or the code and run it again.
Teaching? Assign it to your class in one click.
Beginner About 25 minutes to build and run. Runs in your browser. Free, and no account needed.
Build it as the Halloween Prop Kit: the parts in numbered bags and a booklet that checks every step. Retails for about $66, free on Mokxi.
What you'll learn
- Measuring distance with an ultrasonic ranger
- Turning echo time into centimeters
- Confirming a reading twice before acting
- Hysteresis with two thresholds
- Moving a servo fast, then slowly
- Difficulty: Beginner
- Time: About 25 minutes
- Board: Arduino Uno R3
- Parts: 5
How it works
An HC-SR04 ultrasonic ranger sits on the rim of the bowl and looks across the top. If something is closer than 12 cm for two readings in a row, the sketch decides a hand is reaching in.
Then the servo swings a rubber hand down, the piezo plays a falling cackle, and after 700 ms the arm lifts slowly. The sketch waits until the distance is past 20 cm, then rests for 1.5 seconds so one reach gets one grab.
Parts list
5 parts, plus the jumper wires. They retail for about $36; on Mokxi they're free.
- 1 × Arduino Uno R3In Starter Kit, Claw Machine Kit, Vending Machine Kit.
- 1 × Half breadboard
- 1 × Ultrasonic rangerIn Halloween Prop Kit, Robot Car Kit, Parking Assistant Kit.
- 1 × Hobby servoIn Halloween Prop Kit, Christmas Lights Kit, Starter Projects Kit.
- 1 × Piezo speakerIn Starter Kit, Claw Machine Kit, Vending Machine Kit.
Kits that can build it
These 8 starter kits have every part in the circuit. Each kit's page lists what else it can build.
Wiring table
Every connection, pin by pin, read from the circuit itself. Each row joins the pin on the left to the pin on the right, by a jumper wire or a breadboard strip.
| Part and pin | Connects to |
|---|---|
| Hobby servo pin PWM | Arduino Uno R3 pin 9 |
| Ultrasonic ranger pin ECHO | Arduino Uno R3 pin 8 |
| Ultrasonic ranger pin TRIG | Arduino Uno R3 pin 7 |
| Piezo speaker pin 1 | Arduino Uno R3 pin 4 |
| Ultrasonic ranger pin VCC | Arduino Uno R3 pin 5V |
| Hobby servo pin VCC | Arduino Uno R3 pin 5V |
| Ultrasonic ranger pin GND | Arduino Uno R3 pin GND |
| Hobby servo pin GND | Arduino Uno R3 pin GND |
| Piezo speaker pin 2 | Arduino Uno R3 pin GND |
The code
The firmware exactly as the editor opens it. Change a line there and press Run: it compiles in the browser.
// Grabbing candy bowl: reach in for a treat and the bowl cackles at you while
// a rubber hand swings down to grab yours.
//
// HC-SR04 VCC -> 5 V GND -> GND TRIG -> pin 7 ECHO -> pin 8
// servo PWM -> pin 9, VCC -> 5 V, GND -> GND (the arm under the hand)
// piezo pin 4 -> piezo -> GND (a passive piezo, so tone() sets the note)
//
// Mount the ranger on the rim so it looks across the top of the bowl, not
// down into it: aimed into the bowl it would see the candy and never rest.
// Anything closer than GRAB_CM is a hand.
//
// Two readings in a row have to agree before the hand moves. An ultrasonic
// ranger now and then hears a stray echo, and one bad reading should not
// set off the prop.
//
// The grab itself is a short, fixed show, so it is written as plain steps
// with delay(). After it, the bowl waits for the hand to leave and then
// rests a moment, so one reach gets one grab.
//
// On the bench: a hobby servo's start-up surge can sag the Uno's 5 V, so give
// it a separate 5 V supply with its ground joined to the Uno's. Pad the
// rubber hand's swing so it bumps, never pinches.
//
// Things to try. Drag the ranger's slider under 12 cm. Change the cackle's
// notes. Swap the piezo for a DFPlayer and a speaker for a real recorded
// laugh, as the jump-scare box does.
#include <Servo.h>
const int TRIG_PIN = 7;
const int ECHO_PIN = 8;
const int HAND_PIN = 9;
const int PIEZO_PIN = 4;
const int GRAB_CM = 12; // a hand is closer than this
const int CLEAR_CM = 20; // the hand has gone once it is past this
const int HAND_UP = 20; // degrees, hand raised and hidden
const int HAND_DOWN = 150; // degrees, hand over the bowl
Servo hand;
int closeReadings = 0;
unsigned int grabs = 0;
// Distance in centimeters, or 999 when nothing answers.
int distanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long echo = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (echo == 0) return 999;
return echo / 58; // sound goes there and back, about 58 us per cm
}
void cackle() {
// "Heh heh heh heh-heeeh": short notes falling in pitch, then a long one.
const int notes[] = {880, 784, 698, 622};
for (int i = 0; i < 4; i++) {
tone(PIEZO_PIN, notes[i], 90);
delay(150);
}
tone(PIEZO_PIN, 1047, 400);
}
void grab() {
grabs++;
Serial.print("Grab ");
Serial.println(grabs);
hand.write(HAND_DOWN); // as fast as the servo can go
cackle();
delay(700);
// Lift slowly, which looks far creepier than snapping back.
for (int angle = HAND_DOWN; angle >= HAND_UP; angle -= 5) {
hand.write(angle);
delay(25);
}
}
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
hand.attach(HAND_PIN);
hand.write(HAND_UP);
Serial.println("Candy bowl ready");
}
void loop() {
int cm = distanceCm();
closeReadings = cm < GRAB_CM ? closeReadings + 1 : 0;
if (closeReadings >= 2) {
grab();
// Wait for the hand to leave, then rest a moment.
while (distanceCm() < CLEAR_CM) {
delay(60);
}
Serial.println("Hand gone");
delay(1500);
closeReadings = 0;
}
delay(60);
}
Code walkthrough
The key functions of the sketch, and what each one does.
distanceCm sketch.ino
Sends a 10 microsecond pulse on TRIG, then times the echo on ECHO with pulseIn. Sound travels there and back at about 58 microseconds per centimeter, so it divides by 58. If nothing answers it returns 999.
// Distance in centimeters, or 999 when nothing answers.
int distanceCm() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
unsigned long echo = pulseIn(ECHO_PIN, HIGH, 30000UL);
if (echo == 0) return 999;
return echo / 58; // sound goes there and back, about 58 us per cm
}grab sketch.ino
Counts the grab, sends the servo to HAND_DOWN as fast as it can go, plays the cackle and waits. Then it raises the hand in 5 degree steps with a short delay each, which looks creepier than snapping back.
void grab() {
grabs++;
Serial.print("Grab ");
Serial.println(grabs);
hand.write(HAND_DOWN); // as fast as the servo can go
cackle();
delay(700);
// Lift slowly, which looks far creepier than snapping back.
for (int angle = HAND_DOWN; angle >= HAND_UP; angle -= 5) {
hand.write(angle);
delay(25);
}
}loop sketch.ino
Reads the distance and counts how many readings in a row are under GRAB_CM. At two it calls grab, waits for the hand to move past CLEAR_CM, rests, and starts over.
void loop() {
int cm = distanceCm();
closeReadings = cm < GRAB_CM ? closeReadings + 1 : 0;
if (closeReadings >= 2) {
grab();
// Wait for the hand to leave, then rest a moment.
while (distanceCm() < CLEAR_CM) {
delay(60);
}
Serial.println("Hand gone");
delay(1500);
closeReadings = 0;
}
delay(60);
}Troubleshooting
The usual mistakes with this circuit, and the fix for each.
- It never triggers This project
Check that TRIG is on pin 7 and ECHO on pin 8, and that the ranger is powered from 5V. - It fires constantly This project
The ranger is probably aimed into the bowl and seeing the candy. Mount it so it looks across the top of the bowl. - Distance reads zero, or never changes. Ultrasonic ranger
Power it from 5 V and share ground. Send a 10 microsecond HIGH pulse on TRIG, then time ECHO with pulseIn. Check TRIG and ECHO are not swapped. - Readings jump around or are wrong on a 3.3 V board. Ultrasonic ranger
ECHO outputs 5 V, so divide it down for 3.3 V boards. Aim at flat, hard surfaces. The range is about 2 cm to 4 m, and soft or angled targets bounce the sound away. - The servo jitters, twitches or resets the board when it moves. Hobby servo
Power it from its own 5 V supply, not the Arduino 5 V pin, and join the grounds. A hobby servo can pull several hundred milliamps. Add a 100 uF to 470 uF capacitor across its supply. - The servo hums at the end of its travel or will not reach full angle. Hobby servo
Stay inside the pulse range, about 1000 to 2000 us for most hobby servos. Pushing past the end stop makes it strain. Calibrate the min and max pulse for your servo. - A passive piezo stays silent when you just set the pin HIGH. Piezo speaker
A passive piezo needs a changing signal. Use tone(pin, frequency) or a PWM wave. Around 2 to 4 kHz is loudest. A buzzer with a built in oscillator makes sound from plain DC instead. - Sound is very quiet or the pin seems overloaded. Piezo speaker
Drive the piezo from a pin directly, or through a 100 ohm resistor. For a bigger buzzer, switch it with a transistor. Check that you wired the right two legs and joined grounds.
Change it and keep it
Open it in the editor, change the circuit or the code, and keep your version in a free account.