Skip to content
beginner 30 minSensorSound

Parking Sensor with Buzzer

Measure distance with ultrasound and beep faster as an object gets closer, just like a car's reversing sensor.

The HC-SR04 sends a burst of ultrasound and listens for the echo. Sound travels about 343 metres per second, so the time the echo takes tells you the distance. This project turns that number into beeps.

Build it

  1. 1

    Connect the sensor

    VCC to 5V, GND to GND, Trig to pin 9 and Echo to pin 10.

  2. 2

    Connect the buzzer

    Buzzer positive leg to pin 8 and the other leg to GND.

  3. 3

    Upload and test

    Upload the sketch and move your hand toward the sensor. The beeps speed up below 50 cm and become continuous under 10 cm.

The code

ultrasonic-parking-sensor.ino
const int trig = 9, echo = 10, buzzer = 8;

void setup() {
  pinMode(trig, OUTPUT);
  pinMode(echo, INPUT);
  pinMode(buzzer, OUTPUT);
}

void loop() {
  digitalWrite(trig, LOW);
  delayMicroseconds(2);
  digitalWrite(trig, HIGH);
  delayMicroseconds(10);
  digitalWrite(trig, LOW);
  long cm = pulseIn(echo, HIGH) * 0.0343 / 2;

  if (cm < 10) {
    digitalWrite(buzzer, HIGH);
  } else if (cm < 50) {
    digitalWrite(buzzer, HIGH);
    delay(40);
    digitalWrite(buzzer, LOW);
    delay(cm * 6);
  } else {
    digitalWrite(buzzer, LOW);
  }
}