Parking Sensor: Distance
Part of the Projects section of Coddy's Arduino journey. Lesson 9 of 24.
Cars have parking sensors that beep faster as you back towards a wall. This project builds one: a distance sensor, three warning lights, a buzzer and a screen, all wired already. The first step is the measurement.
As in Displays and Sensors, a 10 microsecond pulse on TRIG sends a ping, and pulseIn(echoPin, HIGH) returns how long ECHO stayed HIGH, in microseconds. Sound takes about 58 microseconds to go one centimetre and come back, so the distance in cm is that time divided by 58 (the same as duration * 0.034 / 2). Keep it all in one function:
long readDistance() {
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);
return duration / 58;
}Measure about ten times a second: the sensor needs a short rest between pings, or a late echo from the last one can be taken for the new one.
Challenge
EasyThe sensor has TRIG on pin 9 and ECHO on pin 10:
- write
readDistance(): the trigger pulse,pulseIn(), and the time divided by 58 - in
loop(), print the distance withSerial.println()every 100 ms
Press Run, drag the distance on the sensor, then Check.
Try it yourself
// The distance sensor
const int trigPin = 9;
const int echoPin = 10;
// Send a ping and return the distance in cm.
long readDistance() {
}
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// print the distance, then wait 100 ms
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Projects
3Parking Sensor
Parking Sensor: DistanceParking Sensor: LightsParking Sensor: BeepsParking Sensor: DisplayPractice on your own: Arduino playground