Hardware Reference
In-Depth Information
Figure 2-13. Wiring an HC-SR04 ultrasonic sensor
Example 2-7
shows BoneScript code used to drive the HC-SR04.
Example 2-7. Driving a HC-SR04 ultrasound sensor (hc-sr04-ultraSonic.js)
#!/usr/bin/env node
// This is an example of reading HC-SR04 Ultrasonic Range Finder
// This version measures from the fall of the Trigger pulse
// to the end of the Echo pulse
var
b
=
require
(
'bonescript'
);
var
trigger
=
'P9_16'
,
// Pin to trigger the ultrasonic pulse
echo
=
'P9_41'
,
// Pin to measure to pulse width related to the
distance
ms
=
250
;
// Trigger period in ms
var
startTime
,
pulseTime
;
b
.
pinMode
(
echo
,
b
.
INPUT
,
7
,
'pulldown'
,
'fast'
,
doAttach
);
function
doAttach
(
x
) {
if
(
x
.
err
) {
console
.
log
(
'x.err = '
+
x
.
err
);
return
;
}
// Call pingEnd when the pulse ends
b
.
attachInterrupt
(
echo
,
true
,
b
.
FALLING
,
pingEnd
);
}
b
.
pinMode
(
trigger
,
b
.
OUTPUT
);
b
.
digitalWrite
(
trigger
,
1
);
// Unit triggers on a falling edge.