Created
May 13, 2018 22:23
-
-
Save jastill/929a09f80c03a44b21b5710cf16c1b81 to your computer and use it in GitHub Desktop.
NPM onoff with closure for Watch
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
/** | |
* Simple code to have notifications (interrupts) when the signal to the input pins change. | |
* | |
*/ | |
const Gpio = require('onoff').Gpio; | |
var sensorPins = [27,22,5,6,13,26,23,18]; | |
var sensors = []; | |
// Loop through each configured sensor and create the onoff | |
for (var i=0; i<sensorPins.length; i++) { | |
// Use a closure to identify the pin in the callback | |
function createSensor(pin) { | |
var sensor = new Gpio(pin,'in','rising', {debounceTimeout:10}) | |
sensor.watch(function (err, value) { | |
if (err) { | |
throw err; | |
} | |
console.log("Pin "+pin+":"+value); | |
}); | |
}; | |
var newSensor = createSensor(sensorPins[i]); | |
sensors.push(newSensor); | |
} | |
/** | |
* Ctrl-c handler | |
*/ | |
process.on('SIGINT', function () { | |
for (var i=0; i<sensorPins.length; i++) { | |
sensors[i].unexport(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment