adafruit / circuitpython

CircuitPython - a Python implementation for teaching coding with microcontrollers
https://circuitpython.org
Other
4.12k stars 1.22k forks source link

Fix regression of keypad.*.reset() behavior: send key_pressed events #9819

Closed dhalbert closed 2 days ago

dhalbert commented 2 days ago

@aseanwatson pointed out that there was a regression from 9.0.0 to 9.1.0 for keypad.*.reset(). It started sending key_released instead of key_pressed events. @aseanwatson also figured out the fix (thanks!), which is what is here.

Also documents how to use reset() to determine which keys are held down at program startup.

Fixes #9818, by fixing the mentioned bug.

Using reset() to determine pressed keys makes a new API unneeded (tagging @todbot on this).

Tested on a CPB:

import board
import keypad
import time

keys = keypad.Keys((board.BUTTON_A, board.BUTTON_B), value_when_pressed=True, pull=True)

while True:
    print("reset in 3 seconds...")
    time.sleep(3)
    keys.events.clear()
    keys.reset()
    while event := keys.events.get():
        print(event)

Confirmed that it worked in 9.0.0, gave the wrong events in 9.1.0, and is fixed by the change.

todbot commented 2 days ago

This works great for my simple cases of detecting a held button on reset/boot. e.g.

import board, keypad, time
keys = keypad.Keys( (board.GP8,), value_when_pressed=False, pull=True )
keys.reset()
if key := keys.events.get():
    print("KEY HELD AT BOOT")
while True:
    print("HI")
    if key := keys.events.get():
        print(key)  # will print release message for held key
    time.sleep(1)