In previous example, we have seen, that when we pressed the button once, multiple outputs were provided. Since the readings on the digital pin occurs with high sampling frequency in the transient period, when the contact is established, the input signal changes states. This would not be convenient for controlling output devices therefore, we should add the debounce algorithm to the .js code.
The hardware setup for the Example 08 is the same as for Example 07.
board.digitalRead on pin 2 is continuously executed, when the input changes from 0->1 or from 1->0. Therefore in the transition period, when the input is not stable, the timeout is first set (setTimeout) and on state change immediately cleared by first if sentence. Therefore started Timeout is cleared by first if sentence, when the state change by clearTimeout(timeout);
When the input is stable, the timeout is set: timeout = setTimeout(function() and after 50ms the write to pin is executed.
var timeout = false;
var last_sent = null;
var last_value = null;
board.digitalRead(2, function(value) { // this happens many times on digital input change of state 0->1 or 1->0
if (timeout !== false) { // if timeout below has been started (on unstable input 0 1 0 1) clear it
clearTimeout(timeout); // clears timeout until digital input is not stable i.e. timeout = false
}
timeout = setTimeout(function() { // this part of code will be run after 50 ms;
// if in-between input changes above code clears it
console.log("Timeout set to false");
timeout = false;
if (last_value != last_sent) { // to send only on value change
if (value == 0) {
console.log("LED OFF");
board.digitalWrite(13, board.LOW);
console.log("value = 0, LED OFF");
}
else if (value == 1) {
console.log("LED ON");
board.digitalWrite(13, board.HIGH);
console.log("value = 1, LED lit");
}
sendValueViaWebSocket(value.toString()); // ws transfers only string
}
last_sent = last_value;
}, 50); // execute after 50ms
last_value = value; // this is read from pin 2 many times per s
}); // end board.digitalRead on pin 2