Search code examples
pythonbuttondebouncing

Why does this debounce function not work?


So I'm trying to make a simple debounce and I just can't figure out where I messed up. Here is the code:

def debounce(var, db):
    if var == 1 and db == 0:
        db = 1
    elif var == 0:
        db = 0
    else:
        var = 0
    return var, db


while True:
    mouse_buttons = get_mouse_buttons()    # -This is the fuction that if the mouse's buttons are pressed

    pressed, db = debounce(mouse_buttons[0], db)
    mouse_buttons = (pressed, 0, 0)

    print(mouse_buttons[0])

My expected output would be if I press the mouse button, then it would be a 1 for once, then turn 0 untill I release and press it again. The current code gives out a 1 for the first time, and no matter what, it only gives out 0 after. (I tested it, it has nothing to do with the function that returns the pressed buttons on the mouse.)


Solution

  • Just to confirm your test expectations

    var  |  db  |  var,db 
    ----------------------
      0     0      0,0
      0     1      0,0
      1     0      1,1
      1     1      0,1
    

    If this is correct then I am not sure that your function does do that.

    This is simpler - to reproduce the same logic table.

    def debounce(var, db):
        return var and not db, var
    

    In this case when var is 0 - this will return 0,0 When var is 1 this will return 1,1 if db == 0 When var is 0 this will return 0,1 if db == 1

    Addendum - when I re-ran your code with get_mouse_buttons() replaced with this :

    def get_mouse_buttons():
        return (int(input('>>').lower()=='y'), 0, 0)
    

    Where you get to decide (by typing Y/y) whether the mouse button is pressed, it turns out that your debounce code - although clunky does actually do what is expected - your loop only prints a 1 when you type a 'y' initially or you go from not a 'y' to a 'y' - ie your code correctly detects the initial change from non-pressed to pressed.

    Since you state your code doesn't work thereofre th clear suspect is your get_mouse_buttons() function - which you have claimed works ok.