Parking Sensor (Ultrasonic + Buzzer)
Beep faster as an object gets closer, like a car parking sensor. Combine an ultrasonic sensor with a buzzer.
Beginner25 min
What you need
Wiring
Hover a pin or a wire to trace the connection.
Code
parking_sensor.ino
// Beep faster as something gets closer (HC-SR04 + buzzer).
const int trigPin = 9, echoPin = 10, buzzer = 8;
long readCm() {
digitalWrite(trigPin, LOW); delayMicroseconds(2);
digitalWrite(trigPin, HIGH); delayMicroseconds(10); digitalWrite(trigPin, LOW);
return pulseIn(echoPin, HIGH) / 58;
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
pinMode(buzzer, OUTPUT);
}
void loop() {
long cm = readCm();
if (cm > 0 && cm < 30) {
int gap = map(cm, 0, 30, 40, 400); // closer = shorter gap = faster beeps
tone(buzzer, 1000); delay(gap);
noTone(buzzer); delay(gap);
} else {
noTone(buzzer);
delay(50);
}
}
Steps
- Wire the HC-SR04: VCC to 5V, GND to GND, Trig to D9, Echo to D10.
- Wire the buzzer: + to D8, − to GND.
- Upload, then move your hand toward the sensor — the beeps speed up as you get closer.