Cars beep faster and faster as you reverse towards a wall. This project does the same with an Arduino, an HC-SR04 ultrasonic sensor and a small buzzer. Mount it in your garage, on a robot, or on a desk to measure how far away things are. You'll learn how ultrasonic sensors measure distance, how to time a pulse in microseconds, and how to make sounds with tone().
What you need
- An Arduino Uno and its USB cable
- An HC-SR04 ultrasonic distance sensor
- A passive piezo buzzer
- A breadboard and six jumper wires
Shopping list (5 items)
Some shop links are affiliate links (Amazon UK, Tooled Up): if you buy through one we may earn a small commission, at no extra cost to you. As an Amazon Associate I earn from qualifying purchases. It never changes which products we recommend, and no shop has paid to be included.
Everything for this build, in one place. One resistor kit and one LED pack cover this project and the others on the site.
- 1×
- 1×HC-SR04 ultrasonic distance sensorThe classic 5 V, four-pin module. The 3.3 V-only variants won't suit a 5 V Uno.
- 1×Passive piezo buzzerPassive, not active: the code plays tones, which needs a passive buzzer. A bare buzzer or a buzzer module both work.
- 1×
- 1×
- FreeArduino IDEThe free Arduino editor. Nothing to buy.
Each button opens that shop's page for the part, checked when we wrote the list; if one shop is out of stock, try the next. Any equivalent part with the same value works.
Starting from nothing? A starter kit gives you the board, a breadboard and many of these parts in one box.
How the sensor works
The HC-SR04 has two round "eyes". One is a speaker, marked T for transmit, and the other a microphone, marked R for receive. Both work at 40 kHz, far too high for people to hear. When you give the Trig pin a 10 microsecond pulse, the sensor sends a short burst of sound. It then sets its Echo pin HIGH and keeps it HIGH until the echo comes back. The longer the Echo pulse, the further away the object.
Sound travels at about 343 metres per second in air at 20 °C, which is 0.0343 cm every microsecond. The sound has to go there and back, so:
distance in cm = echo time in µs × 0.0343 ÷ 2
An echo of 1,000 µs means 1,000 × 0.0343 ÷ 2 ≈ 17 cm. The sensor's datasheet gives a range of 2 cm to 4 m, a beam about 15° wide, and suggests waiting at least 60 ms between measurements so one echo can't be mistaken for the next.
Passive or active buzzer?
An active buzzer has its own oscillator and beeps at one pitch when you give it power. A passive buzzer needs to be driven with a changing signal, which tone() provides, so you can choose its pitch. This project uses a passive piezo buzzer. A small piezo buzzer draws very little current, so it can go straight on a pin. Larger magnetic buzzers draw more current than a pin should supply, so they need a transistor.
The circuit
| Part | Pin | Connect to |
|---|---|---|
| HC-SR04 | VCC | 5V |
| HC-SR04 | Trig | Arduino pin 9 |
| HC-SR04 | Echo | Arduino pin 10 |
| HC-SR04 | GND | GND |
| Buzzer | + (or the longer leg) | Arduino pin 8 |
| Buzzer | − | GND |
The HC-SR04 runs from 5 V and its Echo pin also gives out 5 V, which suits the Uno. On a 3.3 V board such as a Raspberry Pi Pico or an ESP32, the Echo pin needs a voltage divider to bring it down to a safe level.
- Unplug the Uno. Push the HC-SR04's four pins into four separate breadboard rows, with the "eyes" facing out over the edge.
- Wire VCC, Trig, Echo and GND as in the table. Double-check VCC and GND, because swapping them can damage the sensor.
- Put the buzzer in the breadboard and wire it to pin 8 and GND.
Setting up the Arduino IDE
Install the free Arduino IDE from arduino.cc, plug in the Uno, choose Arduino Uno and its port from the board menu at the top, paste the sketch into a new window and click the arrow (Upload). If the upload fails, check you picked the right port, and that the cable carries data rather than only charging.
The sketch
// Parking sensor for an Arduino Uno: an HC-SR04 ultrasonic sensor
// and a passive buzzer. The closer the object, the faster it beeps.
const byte TRIG = 9;
const byte ECHO = 10;
const byte BUZZER = 8;
const float STOP_CM = 10; // closer than this: one steady tone
const float START_CM = 100; // further than this: silence
const int BEEP_HZ = 2000;
const unsigned long BEEP_MS = 60;
unsigned long lastMeasure = 0;
unsigned long lastBeep = 0;
float distance = -1; // -1 means nothing in range
// Returns the distance in cm, or -1 if no echo came back
float measureCm() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH); // a 10 microsecond pulse starts a measurement
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
unsigned long echoUs = pulseIn(ECHO, HIGH, 30000UL); // give up after 30 ms
if (echoUs == 0) return -1;
return echoUs * 0.0343 / 2; // sound travels 0.0343 cm per microsecond, there and back
}
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
Serial.begin(9600);
}
void loop() {
unsigned long now = millis();
if (now - lastMeasure >= 60) { // the HC-SR04 needs about 60 ms between readings
lastMeasure = now;
distance = measureCm();
Serial.println(distance);
}
if (distance < 0 || distance > START_CM) {
noTone(BUZZER); // nothing close: stay quiet
} else if (distance < STOP_CM) {
tone(BUZZER, BEEP_HZ); // very close: steady tone
} else {
// 10 cm gives a beep every 100 ms, 100 cm one every 1000 ms
unsigned long gap = (unsigned long)(distance * 10);
if (now - lastBeep >= gap) {
lastBeep = now;
tone(BUZZER, BEEP_HZ, BEEP_MS); // short beep; tone() stops it by itself
}
}
}
Open the Serial Monitor (the magnifying glass at the top right, set to 9600 baud) to see each measurement in centimetres. -1.00 means nothing was in range. Move your hand towards the sensor: below 100 cm the buzzer starts beeping, the beeps get closer together as you get nearer, and under 10 cm it sounds one steady tone.
How it works
- Measuring.
measureCm()sends the 10 µs trigger pulse, thenpulseIn()times how long Echo stays HIGH, in microseconds. If no echo arrives within 30 ms, which is further than the sensor's 4 m range,pulseIn()gives up and returns 0, and the sketch reports −1. - Timing without
delay(). The sketch measures every 60 ms and decides about beeping on every pass ofloop(), usingmillis()for both. Our guide to millis() vs delay() explains the pattern. - Beep rate. The gap between beeps in milliseconds is the distance in centimetres times 10, so 50 cm gives a beep every half second.
tone(BUZZER, 2000, 60)starts a 60 ms beep at 2 kHz and stops it by itself, so the sketch doesn't have to wait. - Tested. We ran this exact sketch on a simulated Uno with an object moving steadily towards the sensor, checking the trigger pulses, the measured distances and the beep timing.
Accuracy
The speed of sound rises by about 0.6 m/s for each degree Celsius, so on a cold day the sensor reads slightly long and on a hot day slightly short. That's about 2 mm per metre for each degree away from the temperature the code assumes, so on a frosty morning a reading can be a few centimetres per metre out. That still doesn't matter for parking. Soft surfaces such as curtains and clothes absorb sound, and surfaces at a steep angle reflect it away, so either can make readings jump or vanish.
Troubleshooting
- Always −1: Trig and Echo are probably swapped, or VCC isn't connected. Check the wiring against the table.
- Readings jump around: point the sensor at a flat, hard surface, keep its wires short, and make sure nothing is close to the sides of the beam.
- The buzzer clicks but doesn't beep: you may have an active buzzer, which beeps at its own pitch when it gets steady power. A passive one gives the cleanest result.
- PWM stops working on pins 3 or 11: on the Uno,
tone()uses the same timer as PWM on those pins, so use other pins for dimming LEDs or controlling motor speed.
Take it further
- Add green, amber and red LEDs that light at different distances, like the traffic lights project.
- Smooth the readings by taking the middle of the last three measurements, which removes single bad readings.
- Send the distances to your computer and plot them with our guide to reading Arduino serial data in Python.
Sources
The main references behind this guide. Numbers we worked out ourselves, such as the code outputs, come from running the code.