Skip to content

Instantly share code, notes, and snippets.

@GottZ
Created July 29, 2016 20:47
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 GottZ/e4be78c928817c6701155f6ae910d841 to your computer and use it in GitHub Desktop.
Save GottZ/e4be78c928817c6701155f6ae910d841 to your computer and use it in GitHub Desktop.
simple debounce in onoff (nodejs gpio module)
"use strict";
const Gpio = require("onoff").Gpio;
// some kind of debouncing wrapper for watch
Gpio.prototype.watchFilter = function (callback) {
const that = this;
if (!this.watchFilterData) {
const d = this.watchFilterData = {
oldValue: undefined,
timer: undefined,
listener: []
};
this.watch(function (err, value) {
if (err) {
if (d.listener.length == 0) throw err;
d.listener.forEach(l => l.call(that, err, value));
return;
}
clearTimeout(d.timer);
d.timer = setTimeout(function () {
if (d.oldValue === value) return;
d.oldValue = value;
d.listener.forEach(l => l.call(that, undefined, value));
}, 10); // you might need to increase this timer if you experience any problems
});
}
this.watchFilterData.listener.push(callback);
};
// now what the actual code looks like:
const button = new Gpio(3, "in", "both");
button.watchFilter(function (err, value) {
if (err) throw err;
console.log(["off", "on"][value]);
});
@GottZ
Copy link
Author

GottZ commented Jul 29, 2016

related: fivdi/onoff#51

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment