-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathsonar.js
30 lines (23 loc) · 831 Bytes
/
sonar.js
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
const Gpio = require('pigpio').Gpio;
const trigger = new Gpio(18, { mode: Gpio.OUTPUT });
const echo = new Gpio(24, { mode: Gpio.INPUT, alert: true });
trigger.digitalWrite(0); // Make sure trigger is low
// The number of microseconds it takes sound to travel 1cm at 20 degrees celcius
const MICROSECDONDS_PER_CM = 1e6 / 34321;
const watchHCSR04 = () => {
let startTick;
echo.on('alert', (level, tick) => {
if (level == 1) {
startTick = tick;
} else {
const endTick = tick;
const diff = (endTick >> 0) - (startTick >> 0); // Unsigned 32 bit arithmetic
console.log('distance: ', diff / 2 / MICROSECDONDS_PER_CM);
}
});
};
watchHCSR04();
// Trigger a distance measurement once per second
setInterval(() => {
trigger.trigger(10, 1); // Set trigger high for 10 microseconds
}, 1000);