Arduino Parking Sensor with Ultrasonic Sensor
The ultrasonic sensor sends a sound pulse and times the echo, like a bat. The closer the wall, the faster the beeps.
Parts you need
- Arduino Uno
- HC-SR04 ultrasonic sensor
- Piezo buzzer
Wiring
- Sensor VCC → 5V, GND → GND
- Trig → pin 7, Echo → pin 6
- Pin 8 → buzzer → GND rail
Arduino code
int trig = 7;
int echo = 6;
int buzzer = 8;
void setup() {
pinMode(trig, OUTPUT);
pinMode(echo, INPUT);
Serial.begin(9600);
}
void loop() {
digitalWrite(trig, LOW);
delayMicroseconds(2);
digitalWrite(trig, HIGH);
delayMicroseconds(10);
digitalWrite(trig, LOW);
long duration = pulseIn(echo, HIGH);
int distance = duration / 58;
Serial.print("Distance: ");
Serial.print(distance);
Serial.println(" cm");
if (distance < 20) {
tone(buzzer, 1000, 100);
delay(distance * 10 + 50);
} else {
delay(300);
}
}
Goal and tip
Goal: Move the obstacle closer than 20 cm to hear the warning beeps.
Tip: Try this: change 20 to 40 so the alarm starts earlier.