Last active
November 2, 2018 10:18
-
-
Save Pofay/ffaac6e42ddabe808b01359d9f050d26 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* Define a .env file with the following properties | |
MAXIMUM_DISTANCE=7.08 <You can change this to whatever you like> | |
HOST_IP=<IP of HOST Machine that runs this code https://github.com/Pofay/parking-sensor-example-server> | |
PORT=3000 | |
The distance is in centimeters(cm) | |
*/ | |
const Gpio = require('pigpio').Gpio; | |
const axios = require('axios'); | |
require('dotenv').config(); | |
// The number of microseconds it takes sound to travel 1cm at 20 degrees celcius | |
const MICROSECDONDS_PER_CM = 1e6/34321; | |
const url = 'http://' + process.env.HOST_IP + ':' + process.env.PORT + '/api/parking_lot' | |
const trigger = new Gpio(23, {mode: Gpio.OUTPUT}); | |
const echo = new Gpio(24, {mode: Gpio.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 | |
const distance = diff / 2 / MICROSECDONDS_PER_CM; | |
if(distance <= process.env.MAXIMUM_DISTANCE) { | |
axios.put(url, { status: 'occupied' }) | |
.then(res => console.log(res.status)) | |
.catch(console.err) | |
} | |
else { | |
axios.put(url, { status: 'vacant' }) | |
.then(res => console.log(res.status)) | |
.catch(console.err) | |
} | |
} | |
}); | |
}; | |
watchHCSR04(); | |
// Trigger a distance measurement once per second | |
setInterval(() => { | |
trigger.trigger(10, 1); // Set trigger high for 10 microseconds | |
}, 1000); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment