buttons: Debounce gcode_button and filament_switch_sensor (#6848)

Add `debounce_delay` config option which sets the debounce time, defaults to 0

Signed-off-by: Gareth Farrington <gareth@waves.ky>
This commit is contained in:
Gareth Farrington
2025-03-20 16:55:33 -07:00
committed by GitHub
parent 06d65ef5ac
commit 272e815522
6 changed files with 63 additions and 14 deletions

View File

@@ -244,6 +244,33 @@ class HalfStepRotaryEncoder(BaseRotaryEncoder):
BaseRotaryEncoder.R_START | BaseRotaryEncoder.R_DIR_CCW),
)
class DebounceButton:
def __init__(self, config, button_action):
self.printer = config.get_printer()
self.reactor = self.printer.get_reactor()
self.button_action = button_action
self.debounce_delay = config.getfloat('debounce_delay', 0., minval=0.)
self.logical_state = None
self.physical_state = None
self.latest_eventtime = None
def button_handler(self, eventtime, state):
self.physical_state = state
self.latest_eventtime = eventtime
# if there would be no state transition, ignore the event:
if self.logical_state == self.physical_state:
return
trigger_time = eventtime + self.debounce_delay
self.reactor.register_callback(self._debounce_event, trigger_time)
def _debounce_event(self, eventtime):
# if there would be no state transition, ignore the event:
if self.logical_state == self.physical_state:
return
# if there were more recent events, they supersede this one:
if (eventtime - self.debounce_delay) < self.latest_eventtime:
return
# enact state transition and trigger action
self.logical_state = self.physical_state
self.button_action(self.latest_eventtime, self.logical_state)
######################################################################
# Button registration code
@@ -261,6 +288,14 @@ class PrinterButtons:
self.adc_buttons[pin] = adc_buttons = MCU_ADC_buttons(
self.printer, pin, pullup)
adc_buttons.setup_button(min_val, max_val, callback)
def register_debounce_button(self, pin, callback, config):
debounce = DebounceButton(config, callback)
return self.register_buttons([pin], debounce.button_handler)
def register_debounce_adc_button(self, pin, min_val, max_val, pullup
, callback, config):
debounce = DebounceButton(config, callback)
return self.register_adc_button(pin, min_val. min_val, max_val, pullup
, debounce.button_handler)
def register_adc_button_push(self, pin, min_val, max_val, pullup, callback):
def helper(eventtime, state, callback=callback):
if state: