What is an Ultrasonic Sensor?
Ultrasonic sensors, like the HC-SR04, are hobbyist level distance sensors that use an ultrasonic burst of sound, or ping, to measure the distance to objects around it. They are essentially like miniature sonars, as seen on your favourite submarine. (Hunt For Red October, anyone?).
What can it be used for?
As a distance sensor, they’re best used when trying to measure the distance to something. That something could be, for example, a wall or it could be another robot inside a sumo dohyō. Once the location of the object is known, it’s much easier to target or avoid it.
How does it work?
The HC-SR04 requires only two data pins, plus ground and +5V connections. The two data pins are used for a Trigger (which sends the ping out), and the Echo (which measures the return of the ping).
The ping is sent via a tiny speaker on the front, at a frequency of 40kHz, well above our range of hearing. When it hits an object, the sound bounces back. A second speaker cone acts as a microphone to measure the returning signal.
Based on how long it takes for the sound wave to return, and equipped with a little bit of physics, we are able to calculate the distance the sound travelled in order to return to us, and hence the distance of the object.
What are the limitations?
Because the system relies on reflected sound, harder objects will return more of the sound burst, whilst softer objects will absorb more of it. (Can this be used to your advantage?).
The system relies on at least part of the soundwave being reflected back, it is only effective for a defined window (about ±15°), with best results obtained around the 0° mark. Similarly, at least part of the object must be facing towards the object in order to provide a surface capable of reflecting the ping wave.
How do I use it?
- Connect the Trigger and Echo pins, as per the schematic.
- Connect the ground pin
- Connect the +5V pin
- Connect and program your Arduino
- Open the Serial Monitor (terminal / console viewer)
- Measure distances. Win!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
The datasheet is available in the project folder here.
One problem with this code is that pulsein() will wait for the response, up to a certain amount of time. But what happens while the code is waiting? Nothing! Advanced student may like to see the NewPing library, which attempts to solve this issue.