5.14. Case Study: HC-SR04 Ultrasonic Sensor#
The HC-SR04 is one of the most widely used ultrasonic distance sensors in hobbyist robotics and embedded projects. It measures how long it takes for a short burst of ultrasonic sound to travel to an object and reflect back, and from this time-of-flight it calculates distance.
5.14.1. Properties#
The SR04 Ultrasonic distance sensor allows us to measure distances to objects. It has the following properties:
Minimum rangę: 20mm
Maximum range: 4000mm
Accuracy: 3mm
Angle (horizontal field of view): 15 degrees
5.14.2. Electrical Connections#
The sensor needs two electrical connections for control:
Trigger pin (TRIG): tells the sensor to send out a sound pulse.
Echo pin (ECHO): goes high (logic 1) while the sound is travelling out and back, then goes low again when the echo is detected. The length of time this pin stays high is proportional to the round-trip time of the sound wave.
5.14.3. Working Principle#
The sensor has two cylindrical transducers:
One acts as a transmitter, emitting a burst of sound waves at around 40 kHz (well above the human hearing range).
The other acts as a receiver, listening for the echo that bounces back from a nearby object.
5.14.4. Measurement Process#
Trigger the pulse
The microcontroller briefly sets the TRIG pin high for at least 10 microseconds. This command makes the sensor emit a burst of eight ultrasonic pulses.
Wait for the echo
After sending the burst, the sensor sets the ECHO pin high. It stays high while it waits for the reflected sound to return.
Measure the pulse width
When the echo is detected, the ECHO pin goes low. The duration of the high pulse on the ECHO pin corresponds to the round-trip time of the sound.
If no echo is detected within about 38 ms (equivalent to 4 m round-trip), the sensor times out.
If an object is very close, the echo returns quickly and the pulse width is short.
5.14.5. Calculating Distance#
Because the speed of sound in air is about :math:343 m/s (:math:approx 0.0343 cm/µs), the formula to calculate distance is:
The multiplication by 0.01715 comes from:
where the division by 2 is because the pulse travels out and back.