-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
110 lines (84 loc) · 2.36 KB
/
index.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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
const express = require('express');
const gpio = require('onoff').Gpio;
const PiGpio = require('pigpio').Gpio;
const app = express();
const port = 3000;
const MICROSECDONDS_PER_CM = 1e6/34321;
app.get('/', (req, res) => {
console.log("Got a request on /");
res.send('Hello World!');
});
app.listen(port, () => {
console.log(`Robot is listening on port ${port}!`)
});
const blue = new gpio(10, "out");
const red = new gpio(9, "out");
const green = new gpio(11, "out");
const leftLine = new gpio(27, "in", "both");
const rightLine = new gpio(17, "in", "both");
const motion = new gpio(22, "in", "both");
const trigger = new PiGpio(18, {mode: PiGpio.OUTPUT});
const echo = new PiGpio(24, {mode: PiGpio.INPUT, alert: true});
trigger.digitalWrite(0); // Make sure trigger is low
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(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);
const respondWithLight = (err, value, callbackOn, callbackOff)=>{
if (err) {
console.error(`Error reading ${err}`);
}
else {
console.log(`received value ${value}`);
if (value === 1) {
callbackOn();
setTimeout(callbackOff, 5000);
}
else {
callbackOff();
}
}
};
leftLine.watch((err, value)=>{
respondWithLight(err, value, ()=>red.writeSync(1), allLightsOff);
});
rightLine.watch((err, value)=>{
respondWithLight(err, value, ()=>blue.writeSync(1), allLightsOff);
});
motion.watch((err, value)=>{
respondWithLight(err, value, ()=>green.writeSync(1), allLightsOff);
});
const accessible = gpio.accessible;
console.log("gpio is accessible "+accessible);
const allLightsOff = () => {
// console.log("turning the lights off");
blue.writeSync(0);
red.writeSync(0);
green.writeSync(0);
};
const allLightsOn = () => {
// console.log("turning the lights on");
blue.writeSync(1);
red.writeSync(1);
green.writeSync(1);
};
// setTimeout(allLightsOn, 1000);
// Handle Ctrl+C exit cleanly
process.on('SIGINT', () => {
allLightsOff();
process.exit();
});
// allLightsOff();