Bug in Button/Switch Input Example

The example code for the Button/Switch Input has an infinite loop - debounce and switch call each other and there is not a way for the code to terminate.

`// Debounce code: ignore transitions for 50ms after event
local ignore = false;
function debounce() {
// We can take notice of transitions from now onward
ignore = false;

// Ensure state is in sync
switched();

}

// This function is called whenever the imp detects a change on pin1
function switched() {
if (!ignore) {
local s = hardware.pin1.read();

    // Has the state changed?
    if (s != laststate) {
        // Yes, note the state, send it, and update the planner
        laststate = s;
        out1.set(s);
        server.show(s?"on":"off");
        server.log(s?"on":"off");
    }

    // Ignore bounces
    ignore = true;
    imp.wakeup(0.05, debounce);
}

}`

I corrected the code by doing the following (although I’m sure there is a more elegant solution):
`// Debounce code: ignore transitions for 50ms after event
local ignore = false;
function debounce() {
// We can take notice of transitions from now onward
ignore = false;

// Ensure state is in sync
switched(true);

}

// This function is called whenever the imp detects a change on pin1
function switched(calledFromDebounce = false) {
if (!ignore) {
local s = hardware.pin1.read();

    // Has the state changed?
    if (s != laststate) {
        // Yes, note the state, send it, and update the planner
        laststate = s;
        out1.set(s);
        server.show(s?"on":"off");
        server.log(s?"on":"off");
    }

    // Ignore bounces
    if(!calledFromDebounce){
        ignore = true;
        imp.wakeup(0.05, debounce);
    }
}

}`

That’s a good point. (For those following along at home, switched doesn’t call debounce directly, but it does pass it to imp.wakeup, which calls it 50ms later. Then debounce calls switch, which does the imp.wakeup again, so debounce gets called every 50ms forever more. Which is not what was intended.)

Peter