Ultrasonic Echo Time
Part of the Displays and Sensors section of Coddy's Arduino journey. Lesson 18 of 24.
The HC-SR04 measures distance like a bat: it sends a click too high for us to hear and times the echo. The further away the object, the longer the echo takes.
It has two signal pins. A short HIGH pulse on TRIG tells it to click. ECHO then goes HIGH and stays HIGH until the echo comes back, so the length of that HIGH pulse is the time the sound took.
delayMicroseconds() waits in millionths of a second, short enough for the 10 microsecond trigger pulse. pulseIn(pin, HIGH) waits for the pin to go HIGH and returns how many microseconds it stayed HIGH. If no pulse comes within a second it gives up and returns 0.
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10); // the trigger pulse
digitalWrite(trigPin, LOW);
long duration = pulseIn(echoPin, HIGH);An echo can last up to 38000 microseconds, more than an int holds, so keep it in a long.
Challenge
MediumTRIG is on pin 9 and ECHO on pin 10. In loop():
- send a 10 microsecond HIGH pulse on TRIG
- measure the echo with
pulseIn(echoPin, HIGH) - print the time with
Serial.println()
Press Run, move the object closer and further on the board, then Check.
Try it yourself
const int trigPin = 9;
const int echoPin = 10;
void setup() {
pinMode(trigPin, OUTPUT);
pinMode(echoPin, INPUT);
Serial.begin(9600);
}
void loop() {
// send a 10 microsecond pulse on TRIG
// time the echo with pulseIn() and print it
delay(200);
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Displays and Sensors
1Seven-Segment Displays
Seven-Segment DisplayDigit Patterns in BytesCount on the DisplayCountdown to ZeroDice RollerPractice on your own: Arduino playground