Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
NPM onoff with closure for Watch
/**
* 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