Back to Projects
IntermediateArduino Uno R3
35 minutes build
Parking sensor
An ultrasonic sensor with beeps that speed up as an obstacle approaches.
Interactive Simulation
Parking sensorarduino-uno
Required Components Checklist
Assembly Steps
1
Connect the sensor
VCC to 5V, GND to GND, TRIG to pin 7, ECHO to pin 6.
2
Measure
Send a 10 µs pulse, time the echo with pulseIn() and divide by 58 for centimetres.
3
Give feedback
Map the distance to the pause between beeps; light the LED when closer than 20 cm.
Arduino Sketch
const int TRIG = 7;
const int ECHO = 6;
const int BUZZER = 8;
const int LED = 12;
long readCm() {
digitalWrite(TRIG, LOW);
delayMicroseconds(2);
digitalWrite(TRIG, HIGH); // a 10 µs pulse starts a measurement
delayMicroseconds(10);
digitalWrite(TRIG, LOW);
long us = pulseIn(ECHO, HIGH, 30000); // echo time in µs (0 = nothing in range)
return us / 58; // sound: ~58 µs per cm, there and back
}
void setup() {
pinMode(TRIG, OUTPUT);
pinMode(ECHO, INPUT);
pinMode(LED, OUTPUT);
Serial.begin(9600);
}
void loop() {
long cm = readCm();
Serial.print(cm);
Serial.println(" cm");
if (cm > 0 && cm < 100) {
digitalWrite(LED, cm < 20 ? HIGH : LOW);
tone(BUZZER, 1000, 60);
delay(map(cm, 0, 100, 60, 600)); // closer = faster beeps
} else {
digitalWrite(LED, LOW);
delay(300);
}
}
Challenges & Extensions
Ready to take this project further? Try these challenges:
- •Make a continuous tone below 10 cm.
- •Average 5 readings to smooth out jumps.
- •Add a second LED for a green/red indicator.