@@ -127,3 +127,58 @@ def last_duration(self):
127
127
def current_duration (self ):
128
128
"""Return the number of seconds since the most recent transition."""
129
129
return ticks_diff (ticks_ms (), self ._state_changed_ticks ) / _TICKS_PER_SEC
130
+
131
+
132
+
133
+ class Button (Debouncer ):
134
+ """Debounce counter"""
135
+ def __init__ (self , pin , short_duration = 0.2 , long_duration = 0.5 , active_down = True , ** kwargs ):
136
+ self .short_duration = short_duration
137
+ self .long_duration = long_duration
138
+ self .active_down = active_down
139
+ self .last_change_ticks = ticks_ms ()
140
+ self .short_counter = 0
141
+ self .short_showed = 0
142
+ self .long_registered = False
143
+ self .long_showed = False
144
+ super (Button , self ).__init__ (pin , ** kwargs )
145
+
146
+ def pushed (self ):
147
+ return (self .active_down and super ().fell ) or (not self .active_down and super ().rose )
148
+
149
+ def released (self ):
150
+ return (self .active_down and super ().rose ) or (not self .active_down and super ().fell )
151
+
152
+ def update (self ):
153
+ super ().update ()
154
+ if self .pushed ():
155
+ self .last_change_ticks = ticks_ms ()
156
+ self .short_counter = self .short_counter + 1
157
+ elif self .released ():
158
+ self .last_change_ticks = ticks_ms ()
159
+ if self .long_registered :
160
+ self .long_registered = False
161
+ self .long_showed = False
162
+ else :
163
+ now_ticks = ticks_ms ()
164
+ duration = ticks_diff (now_ticks , self .last_change_ticks )
165
+ if not self .long_registered and self .value != self .active_down and duration > self .long_duration :
166
+ self .long_registered = True
167
+ self .short_showed = self .short_counter - 1
168
+ self .short_counter = 0
169
+ elif self .short_counter > 0 and self .value == self .active_down and duration > self .short_duration :
170
+ self .short_showed = self .short_counter
171
+ self .short_counter = 0
172
+
173
+ @property
174
+ def short_count (self ):
175
+ ret = self .short_showed
176
+ self .short_showed = 0
177
+ return ret
178
+
179
+ @property
180
+ def long_press (self ):
181
+ if self .long_registered and not self .long_showed :
182
+ self .long_showed = True
183
+ return True
184
+ return False
0 commit comments