⭐⭐ Advanced beginner
⏱️ 20 minutes
Parking sensor
You build a parking sensor, just like in a car. The closer you get to the sensor, the faster the buzzer beeps. Very close? Then you hear one long tone.
🧰 What do you need?
🗺️ Wiring diagram
Follow the wires from the Arduino to each part. You can choose the wire colors yourself.
| From | To |
|---|---|
Arduino UNO · D9 |
Distance sensor HC-SR04 · Trig |
Arduino UNO · D10 |
Distance sensor HC-SR04 · Echo |
Arduino UNO · 5V |
Distance sensor HC-SR04 · Vcc |
Arduino UNO · GND |
Distance sensor HC-SR04 · Gnd |
Arduino UNO · D8 |
Active buzzer · S |
Arduino UNO · 5V |
Active buzzer · + |
Arduino UNO · GND |
Active buzzer · - |
🛠️ This is how you build it
- Connect the HC-SR04: Trig to pin 9, Echo to pin 10, Vcc to 5V and Gnd to GND.
- Connect the buzzer: S to pin 8, + to 5V and − to GND.
- Use the + and − strips on your breadboard for 5V and GND.
💻 The code
// Parking sensor
// The closer you get to the sensor, the faster the buzzer beeps. Just like in a car!
const int TRIG_PIN = 9; // Trig of the HC-SR04 on pin 9
const int ECHO_PIN = 10; // Echo of the HC-SR04 on pin 10
const int BUZZER_PIN = 8; // S of the buzzer on pin 8
void setup() {
Serial.begin(9600);
pinMode(TRIG_PIN, OUTPUT);
pinMode(ECHO_PIN, INPUT);
pinMode(BUZZER_PIN, OUTPUT);
}
// Measure the distance in centimeters
long measureDistance() {
digitalWrite(TRIG_PIN, LOW);
delayMicroseconds(2);
digitalWrite(TRIG_PIN, HIGH); // Send a short sound (you cannot hear it)
delayMicroseconds(10);
digitalWrite(TRIG_PIN, LOW);
long duration = pulseIn(ECHO_PIN, HIGH, 30000); // How long until the echo comes back?
if (duration == 0) return 999; // No echo: nothing nearby
return duration / 58; // Convert time to centimeters
}
void loop() {
long distance = measureDistance();
Serial.print(F("Distance: "));
Serial.print(distance);
Serial.println(F(" cm"));
if (distance < 5) {
digitalWrite(BUZZER_PIN, HIGH); // Very close: one long tone
delay(100);
} else if (distance < 50) {
digitalWrite(BUZZER_PIN, HIGH); // Short beep
delay(50);
digitalWrite(BUZZER_PIN, LOW);
delay(distance * 10); // Closer = shorter pause = faster beeps
} else {
digitalWrite(BUZZER_PIN, LOW); // Far away: quiet
delay(100);
}
}
🧠 What does the code do?
measureDistance()sends a sound and measures how long it takes for the echo to come back. We turn that into centimeters.- More than 50 cm away: the buzzer is quiet.
- Closer: the pause between the beeps gets shorter. Under 5 cm it beeps without stopping.
🎯 Try this…
- Make the parking sensor start beeping from 1 meter away
- Add a red LED that lights up when it is too close
- Show the distance in the serial monitor, with a little bar of stars
🚀 Build this project with Codey: open codey.online/starter-kits/uno/projects/parking-sensor and click MAKE THIS. Then the code and the wiring diagram are ready right away.
Codey Online is a product of OTRONIC