Hardware Reference
In-Depth Information
Discussion
The HC-SR04 works by sending a 40 kHz ultrasonic pulse out when a 10 μs (or longer)
pulse appears on its
Trigger
input. The
Echo
output produces a pulse whose length is in
proportion to the distance that was measured.
The HC-SR04 is a 5 V device that outputs a 5 V pulse on its
Echo
port, which is too much
for the Bone's GPIOs, which expect 0 and 3.3 V. A simple resistor divider network is used
to scale the 5 V down to 3.3 V. We use 20 kΩ and 10 kΩ resistors for the divider, but other
pairs will work as long as the ratio is 2 to 1. But be careful: if you make them too big (say,
100 kΩ and 200 kΩ), the GPIO port will draw too much current through it and make the
output voltage sag too much. If you make the resistors too small, you will pull a lot of cur-
rent through them, wasting power.
setInterval()
and
ping()
to pull
trigger
low at a regular interval and start a
timer.
attachInterrupt()
and
pingEnd()
are used to wait for
echo
to fall to
0
.
Once it does,
pingEnd()
is called, and it computes the time since
ping()
started and
sets
trigger
back to
1
, so everything can start over again.
seconds. (JavaScript's built-in timer gives only
ms
results.) The code converts the nano-
seconds to milliseconds and then subtracts 0.8 ms. The 0.8 ms is the approximate time from
when the trigger falls to when the pulse is sent out. (This is a measured result, not from the
datasheet.)
But how accurate is it? I attached an oscilloscope to the
Echo
pin and measured pulses with
widths from 0.5 to 5 ms. The oscilloscope measured a 25 μs standard deviation, which rep-
resents the device's repeatability and the stability of the person holding the target. With the
0.8 ms correction, the Bone appeared to measure the pulse width to within 0.2 ms or so,
which is around 4 cm. Not bad for using JavaScript and probably close enough for most ro-
botics applications.