Skip to content

Instantly share code, notes, and snippets.

@jasonblewis
Created September 15, 2018 23:08

Revisions

  1. jasonblewis created this gist Sep 15, 2018.
    68 changes: 68 additions & 0 deletions switchdebounce.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,68 @@
    import machine
    from machine import Timer
    # see listing one
    # https://www.embedded.com/electronics-blogs/break-points/4024981/My-favorite-software-debouncers

    np = machine.Neopixel(15,8,machine.Neopixel.TYPE_RGB)

    button = machine.Pin(34,machine.Pin.IN)

    check_msec = 20
    press_msec = 10
    release_msec = 100
    count = release_msec / check_msec

    RawKeyPressed = False
    DebouncedKeyPress = False

    key_changed = False
    key_changed = False

    def key_pressed_cb(kc, kp):
    print("key changed: ", kc)
    print" key pressed: ", kp


    def tcb(timer):
    global check_msec
    global RawKeyPressed
    global DebouncedKeyPress
    global count
    global key_pressed
    global key_changed
    global button

    key_changed = False;
    key_pressed = DebouncedKeyPress
    RawState = button.value()
    if (RawState):
    #set the timer which will allow a c hange from the current state.
    if (DebouncedKeyPress):
    count = release_msec / check_msec
    else:
    count = press_msec / check_msec
    else:
    # key has changed - wait for new state to become stable
    count -= 1
    if (count == 0):
    # timer expired - accept the change.
    DebouncedKeyPress = RawState
    key_changed = True
    key_pressed = DebouncedKeyPress
    key_pressed_cb(key_changed,key_pressed)
    # and reset the timer
    if (DebouncedKeyPress):
    count = release_msec / check_msec
    else:
    count = press_msec / check_msec






    t1 = machine.Timer(2)
    t1.init(period=check_msec, mode=t1.PERIODIC,callback=tcb)

    while True:
    print("key pressed: ", key_pressed)