Skip to content

Instantly share code, notes, and snippets.

@jastill
Created May 13, 2018 22:23
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jastill/929a09f80c03a44b21b5710cf16c1b81 to your computer and use it in GitHub Desktop.
Save jastill/929a09f80c03a44b21b5710cf16c1b81 to your computer and use it in GitHub Desktop.
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