Hi everyone, today we are going to learn how to use a HC-SR04 ultrasonic sensor. It is a useful device that measure the time spent by a beam of sound waves, emitted from a source, to come back again, after they had been reflected by an obstacle. Starting from this information, we are able to calculate the distance from the sensor to the object. The beam of sound waves has a conical shape, as well as the reflected beam; therefore, it’s impossible for the sensor to distinguish an object from another.
The HC-SR04 sensor can measure correctly distance for values between 2 centimeters and 4 meters, with an error of few millimeters. For further information, consult the datasheet.
The speed of sound vary according to the temperature of the environment. Let’s assume the temperature of the environment is 20°C: the speed v of sound is 343,3 m/s. The sensor returns the measured time in microseconds (µs); however, may be useful to calculate the distance in centimeters. So, we calculate the speed of sound in cm/µs: 1 m/s = 10^2 cm / 10^6 µs = 10^-4 cm/µs => V = 343,5 m/s * 10^-4 = 3,4*10^-2 cm/µs. Now, we calculate the distance traveled by the sound wave: s = v*t = 3,4*10^-4 * t. Pay attention: the wave travel the same distance twice, going and return. In conclusion, the final formula for calculating the distance is:
S = 1,7 * 10^-2 * t
The HC-SR04 sensor
The HC-SR04 has 4 pins: Vcc (+5V), Trigger, Echo and GND. You send a high impulse on the Trigger pin for 10 microseconds. In this way, the sensor send the sound waves and waits for its return. Then, the sensor will respond on the Echo pin, with an high impulse of duration directly proportional to the duration of the sound waves’ travel. You need to wait at least 60 milliseconds from an impulse to another one, in order to avoid interferences with the next measurement.
You just have to connect the Vcc and GND pins respectively to 5V power and ground, and Trigger and Echo pins to two digital pins on the Arduino.
This is the sketch that calculate and show the distance measured with the sensor. It uses digital pin 7 for Trigger and 8 for Echo.