How to measure distances fast, easy and cheap? Ultrasonic is here propably the right answer. Here I want to show how to achieve this with the HC-SR04 ultrasonic module. I've choosen this module because it is very cheap (about 1€ to 2€) and relatively accurate.
Ultrasonic distance measuring works with the speed of sound (~343.2m/s in dry air). First you have to think about, that sound needs in dry air for 343.2 meter only one second. If you count the time between sending a soundwave and receiving it you can recalculate distance it has traveled. Please not, that the speed of sound depends on the used material. In steel it is about 6000m/s longitudinally (and about 3200m/s transversal). It also depends on the temperature.
The object you want to know the distance to must have a minimum size, so the soundwaves can be reflected correctly. For this module the size must be about 0.5m². That way it should work for any distance in the range of the module.
It's simple, just get the following components:
|1||Arduino||Uno or Nano|
I've wired it so, that Echo is connected to pin 2 and Trig to pin 3. The power supply is Vcc5V, and GND is connected to the ground.
The small display is explained here. The display is optional, but it's nice to have the distance side by side with the module.
The code's on GitHub.
The getDistance() function returns the distance between the sensor and the nearest valid object in centimeter. To understand the functions content you also have to understand how the sensor works.
If you activate the Trig-Pin for at least 10 microseconds (+5V) then it starts to send 8 cycles of 40kHz sound waves. The moment it recognizes the reflected waves it sets the Echo-Pin HIGH (+5V).
This is used to calculate the distance. For this I'm using the pulseIn()-function from Arduino. It returns the time in microseconds between the changing from LOW to HIGH.
Now you have to convert the time to a distance. This works with the speed of sound (remember, it was 343.2m/s in dry air), which is 2.9138µs/mm. Note, that sensor and receiver are side by side, so the way the soundwaves travels needs to be doubled → 5.8275μs/mm.
Finally you have to devide the durration of the pulse-changing with this constant. Now you have the distance in millimeter.
The delay of 250 milliseconds is just for the display. If you want to run a time critical code just delete it.
The minimum distance between sensor and object results out of the time-distance between the sent and received soundwave. If both would overlap (not enough time between both) you couldn't tell which one is the received one.
If you want to run two HC-SR04 modules you need 2 Trig-Pins and 2 Echo-Pins. Then you need two separate functions ( getDistance1() & getDistance2() ) or you're going to use a class -> easy going.
Questions and comments: deloarts.wordpress.com