HC-SR04 Ultrasonic Distance Sensor
The HC-SR04 Ultrasonic distance sensor uses ultrasound pulses to measure distance.
It fires 8 'pulses' of ultrasound and records how long it takes to reflect back from an object.
Some objects (hard flat surfaces) reflect ultrasound very well. Others, such as fabric, people etc - not quite so well.
The official specification shows that the sensor has a minimum range of 2cm and maximum of 4m. Resolution is supposed to be 0.3cm - however this is dependent on the object detected.
The datasheet can be found at HC-SR04 User's_Manual - Google Docs
As a test circuit - I connected the sensor directly to an Arduino Uno. With digital pin 2 -> vcc, 3 to trig, 4 to echo and 5 to ground. The sensor conveniently plugs directly into the Arduino...
Power is provided by setting d2 to 5v (1) and d5 to gnd (0). I added a trigger and echo pin to the panel properties.
Looking at the signal from the sensor using an oscilloscope - reveals that the sensor gives a clear pulse for the time of flight measurement..
The top trace shows the 'trigger' pulled high by the Arduino for 10us and the lower trace shows the 'echo' from the sensor.
There are several ways to time the pulse - I used a timer interrupt on timer 2 - setting the prescaler to 1:1 means this runs at 62500Hz - so each 'tick' is 16us - limiting the resolution to 0.27cm (almost the 0.3cm claimed!)
The program simply sends a trigger pulse - then waits for the echo pin to go high. The 'tick' count is reset to 0. Then it waits for the pin to go low - and takes the value of the tick count.
The distance (in cm) is time of flight tof (microseconds) / 58 - because each tick here is 16us - I get a formula of distance = tof / 3.625 (58 / 16)
For a test case - the program simply outputs the distance to UART. For improved accuracy - it would be necessary to use a higher resolution timer. It would also be useful to measure several readings and take an average (and maybe discard any that differ massively from the rest)
This sample will only work on Arduino - though the techniques are applicable to other MCUs - for easier coding - try the HC-SR04 component. Coming soon.