Can't get DebounceIn to work

25 Oct 2014

I'm trying some basic things with a Nucleo F401RE, and I cannot get the most simplistic DebounceIn working. In this case I'm simply setting the LED to the button state. This works perfectly fine using DigitalIn to read the button state:

#include "mbed.h"
#include "DebounceIn.h"

DigitalOut myled(LED1);
DigitalIn pb(PC_13);

int main() {
    pb.mode(PullUp);
    while (1) {
        myled=!pb.read();
    }
}

As long as the button is pressed, the LED illuminates. Now if I simply change the type of pb to DebounceIn, then pb.read() always returns false and thus the LED is always on:

#include "mbed.h"
#include "DebounceIn.h"

DigitalOut myled(LED1);
DebounceIn pb(PC_13);

int main() {
    pb.mode(PullUp);
    while (1) {
        myled=!pb.read();
    }
}

I've tried adding a wait in the loop, commented out the code that enables the internal pull up resistor, etc, and it simply does not work correctly with DebounceIn. Any suggestions would be greatly appreciated. PS, the mbed library is the most recent - version 89.

27 Oct 2014

Hi Dan,
I tried to run your program in my F401RE board and result is same as you.
Then I inserted "printf" in "DebounceIn.h" and found a problem.
As a conclusion, please try below program.

#include "mbed.h"
#include "DebounceIn.h"

DigitalOut myled(LED1);
DebounceIn pb(PC_13);
 
int main() {
    // Please add below line for F401RE (You don't need for L152RE)
    pb.set_debounce_us(1000);
    pb.mode(PullUp);
    while (1) {
        myled=!pb.read();
    }
}

Problem looks like start-up, initialize process before calling the main() routine. "set_debounce_us(1000)" was called at initialize process but not connect "_callback()" routine in the Lib. program.
I'm running same program on L152RE board and no problem without "pb.set_debounce_us(1000);" line.

REMARK: Bounce time for F401RE button (tactile switch) is 5mSec max (not specified it but similar switch in the market).
Above setting time is 10mS. Please choose best value of that.

26 Oct 2014

Thanks, good find! Another fix is to move the DebounceIn declaration inside the scope of the main function:

#include "mbed.h"
#include "DebounceIn.h"

DigitalOut myled(LED1);
Serial pc(SERIAL_TX, SERIAL_RX);
 
int main() {
    DebounceIn pb(PC_13);
    pb.mode(PullUp);
    while (1) {
        myled=!pb.read();
    }
}

I was getting a bit disheartened with such a simple thing not working. It's still concerning to see such basic functionality as object construction in the global scope not working correctly, but hopefully I happened to find one of the rare bugs. :) Thanks again for taking the time to debug this problem.

01 Apr 2016

You should check out Dr Marty's Switch Debouncer. It's faster than DebounceIn, and it works well with both shift registers and PortIn.

https://developer.mbed.org/users/BlueStorm/code/DrMartysSwitchDebouncer