Created
July 29, 2016 20:47
-
-
Save GottZ/e4be78c928817c6701155f6ae910d841 to your computer and use it in GitHub Desktop.
simple debounce in onoff (nodejs gpio module)
This file contains hidden or 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
"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]); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
related: fivdi/onoff#51