Skip to content

Commit 5723369

Browse files
committed
Use debouncer to handle button analysis
1 parent 4f1f480 commit 5723369

File tree

1 file changed

+23
-8
lines changed

1 file changed

+23
-8
lines changed

adafruit_cursorcontrol/cursorcontrol_cursormanager.py

Lines changed: 23 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
from micropython import const
3232
import analogio
3333
from gamepadshift import GamePadShift
34+
from adafruit_debouncer import Debouncer
3435

3536
# PyBadge
3637
PYBADGE_BUTTON_LEFT = const(128)
@@ -50,8 +51,9 @@ class CursorManager:
5051
"""
5152
def __init__(self, cursor):
5253
self._cursor = cursor
53-
self._is_clicked = False
54+
self._pressed = 0
5455
self._init_hardware()
56+
self._debouncer = Debouncer(lambda: bool(self._pressed & self._pad_btns['btn_a']))
5557

5658
def __enter__(self):
5759
return self
@@ -90,21 +92,34 @@ def _init_hardware(self):
9092
digitalio.DigitalInOut(board.BUTTON_OUT),
9193
digitalio.DigitalInOut(board.BUTTON_LATCH))
9294

95+
9396
@property
9497
def is_clicked(self):
9598
"""Returns True if the cursor button was pressed
9699
during previous call to update()
97100
"""
98-
return self._is_clicked
101+
return self._debouncer.rose
102+
pressed = is_clicked
103+
104+
@property
105+
def released(self):
106+
"""Returns True if the cursor button was released
107+
during previous call to update()
108+
"""
109+
return self._debouncer.fell
110+
111+
@property
112+
def held(self):
113+
"""Returns True if the cursor button is currently being held
114+
"""
115+
return self._debouncer.value
116+
99117

100118
def update(self):
101119
"""Updates the cursor object."""
102-
pressed = self._pad.get_pressed()
103-
self._check_cursor_movement(pressed)
104-
if self._is_clicked:
105-
self._is_clicked = False
106-
elif pressed & self._pad_btns['btn_a']:
107-
self._is_clicked = True
120+
self._pressed = self._pad.get_pressed()
121+
self._check_cursor_movement(self._pressed)
122+
self._debouncer.update()
108123

109124
def _read_joystick_x(self, samples=3):
110125
"""Read the X analog joystick on the PyGamer.

0 commit comments

Comments
 (0)