Search code examples
javascriptnode.jsioraspberry-pirate-limiting

Filtering input by frequency (onoff debounce)


I'm using node on raspberry pi and module onoff to get input. I want to only run function B if the function A is called twice in one minute

var gpio = require('onoff').Gpio;
var sensor = new gpio(7, 'in', 'falling');
var timeout = 60000;
var timeOfLastChange;
sensor.watch(function(err, value) {
    console.log('Sensor value is now '+ value);
    var currentTime = new Date(); //2 tick filter
    if(value == false && timeOfLastChange < currentTime - timeout) var timeOfLastChange = new Date();
    if(timeOfLastChange > currentTime - timeout) functionB();  
});
gpio.setup(7, gpio.DIR_IN);

But this doesn't work.


Solution

  • if you change your date evaluations to milliseconds to match your timeout (int to int), then your date comparisons will work. something like this:

    timeOfLastChange.getTime() > (currentTime.getTime() - timeout)
    

    Or even better, don't use the date object, just the epoch millis like this:

    currentTime = Date.now();
    timeOfLastChange = Date.now();
    

    Then your 'times' are an integer-like number, matching your timeout.