Skip to content

Add timing properties as per ATMakersBill's suggestion #11

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Oct 14, 2019
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 15 additions & 1 deletion adafruit_debouncer.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ class Debouncer(object):

def __init__(self, io_or_predicate, interval=0.010):
"""Make am instance.
:param DigitalInOut/function io_or_predicate: the pin (from board) to debounce
:param DigitalInOut/function io_or_predicate: the DigitalIO or function to debounce
:param int interval: bounce threshold in seconds (default is 0.010, i.e. 10 milliseconds)
"""
self.state = 0x00
Expand All @@ -70,6 +70,8 @@ def __init__(self, io_or_predicate, interval=0.010):
self._set_state(_DEBOUNCED_STATE | _UNSTABLE_STATE)
self.previous_time = 0
self.interval = interval
self._previous_state_duration = 0
self._state_changed_time = 0


def _set_state(self, bits):
Expand Down Expand Up @@ -102,6 +104,8 @@ def update(self):
self.previous_time = now
self._toggle_state(_DEBOUNCED_STATE)
self._set_state(_CHANGED_STATE)
self._previous_state_duration = now - self._state_changed_time
self._state_changed_time = now


@property
Expand All @@ -120,3 +124,13 @@ def rose(self):
def fell(self):
"""Return whether the debounced value went from high to low at the most recent update."""
return (not self._get_state(_DEBOUNCED_STATE)) and self._get_state(_CHANGED_STATE)

@property
def last_duration(self):
"""Return the amount of time the state was stable prior to the most recent transition."""
return self._previous_state_duration

@property
def current_duration(self):
"""Return the time since the most recent transition."""
return time.monotonic() - self._state_changed_time
21 changes: 21 additions & 0 deletions examples/debouncer_timing_test.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import time
import board
from digitalio import DigitalInOut, Direction, Pull
from adafruit_debouncer import Debouncer

button = DigitalInOut(board.D4)
button.direction = Direction.INPUT
button.pull = Pull.UP
switch = Debouncer(button)

while True:
switch.update()
if switch.fell:
print('pressed')
print('was released for ', switch.last_duration)
elif switch.rose:
print('released')
print('was pressed for ', switch.last_duration)
else:
print('Stable for ', switch.current_duration)
time.sleep(0.1)