Measuring Distance with HC-SR04
Learn how to measure distance with a HC-SR04 ultrasonic sensor.
How does it work?
Measuring Duration
The HC-SR04 combines an ultrasonic transmitter and receiver. To take a measurement, an ultrasonic wave will be emitted by the transmitter, this wave will then bounce off any objects and get sent back towards the receiver which will pick it up. We can use the duration between the wave being emitted to when it is picked up by the receiver to calculate distance.
Calculating Distance
The speed of sound is approximately 343 meters per second, but we want centimeters per microsecond which is 0.0343 cm/µs. We can then multiply our duration by this number to get the total distance traveled by the wave to the object and back. To get just the distance to the object we can divide it by two.
The Code
The HC-SR04 has only four pins and only two of them we use in the code. One is our trig pin to start a measurement and the other is our echo pin to receive data.
Triggering a Measurement
Before we trigger a measurement by setting the trig pin to high, we need to clear the trig pin incase it's already high. Set the trig pin to low and delay for 2 microseconds to ensure the module has enough time to register it.
digitalWrite(trig, LOW);
delayMicroseconds(2);
Now that trig has been cleared, we can start a measurement, do this by setting trig to high for 10 microseconds.
digitalWrite(trig, HIGH);
delayMicroseconds(10);
Reading the Result
Once a measurement has been started the echo pin will be set to high, we then need to measure the time until it becomes low again and this is our round-trip time. This can be done easily with Arduino's pulseIn function. We want to measure how long it's in the high state so we will use the following code.
long duration = pulseIn(echoPin, HIGH);
Calculating the Distance
this part is easy, we have the speed of sound of sound in cm/µs which is 0.0343, now we just need to multiply the duration by this value and divide it by two to turn the round-trip distance into a one-way distance.
int distance = duration * 0.034 / 2;
Using the Distance
Now you have the distance you can do whatever you want with it. If you'd like to learn how to visualize it with Arduino IDE's serial plotter check out Using Arduino IDE's Serial Plotter.