Sensors
Distance alarm
A sensor that beeps when something comes closer than 20 cm. The same idea as a car's parking sensor.
- Medium
- about 30 min
- Arduino Uno
- No soldering
- 6 parts
- 6 wires
- 28 lines of code
Opens this circuit, already wired, with the sketch loaded. Free, nothing to install.
Idea
Put it on a desk, a shelf or a bedroom door. The sensor sends out a sound too high to hear and times the echo, so it measures distance without touching anything.
What you learn
Timing an echo with pulseIn(), turning a time into centimetres, and making a decision with if.
How it works
input
HC-SR04 distance sensor
decides
Arduino Uno
output
Buzzer
Powered with 5 V from the Uno's USB cable. No battery and no soldering.
This circuit and sketch are run in the ManuStem simulator before the pack is published. Real parts vary between makers: follow the labels printed on your own module, not its position in the picture.
Parts
0 of 6 ready
No prices here: they change by shop and by week. Buy each part by its name and the note beside it.
You also need
A computer with Arduino IDE 2 installed (free)
3D wiring
One jumper per step. Unplug the USB cable while you wire.
Step 0 of 6
Lay out the parts
Push the small parts into the breadboard as shown. Nothing is connected yet.
All connections
distance-alarm.ino
// Distance alarm
// ManuStem Build Pack: https://stem.manusignal.com/packs/distance-alarm
const int TRIG_PIN = 7;
const int ECHO_PIN = 6;
const int BUZZER_PIN = 8;
const int CLOSE_CM = 20;
void setup() {
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
void loop() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH);
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000);
int cm = duration / 58;
if (cm > 0 && cm < CLOSE_CM) {
tone(BUZZER_PIN, 880);
} else {
noTone(BUZZER_PIN);
}
delay(50);
}
Libraries
None. It uses only what the Arduino IDE has built in.
Uploading
- Open the sketch in Arduino IDE.
- Plug the Uno in with the USB cable.
- Tools > Board > Arduino Uno, then Tools > Port and choose the board's port.
- Press Upload (the arrow). Wait for “Done uploading”.