Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
microPython button irq debouncing
import time
from micropython import const
from machine import Pin, Timer
BUTTON_A_PIN = const(32)
BUTTON_B_PIN = const(33)
class Button:
"""
Debounced pin handler
usage e.g.:
def button_callback(pin):
print("Button (%s) changed to: %r" % (pin, pin.value()))
button_handler = Button(pin=Pin(32, mode=Pin.IN, pull=Pin.PULL_UP), callback=button_callback)
"""
def __init__(self, pin, callback, trigger=Pin.IRQ_FALLING, min_ago=300):
self.callback = callback
self.min_ago = min_ago
self._blocked = False
self._next_call = time.ticks_ms() + self.min_ago
pin.irq(trigger=trigger, handler=self.debounce_handler)
def call_callback(self, pin):
self.callback(pin)
def debounce_handler(self, pin):
if time.ticks_ms() > self._next_call:
self._next_call = time.ticks_ms() + self.min_ago
self.call_callback(pin)
#else:
# print("debounce: %s" % (self._next_call - time.ticks_ms()))
def button_a_callback(pin):
print("Button A (%s) changed to: %r" % (pin, pin.value()))
def button_b_callback(pin):
print("Button B (%s) changed to: %r" % (pin, pin.value()))
button_a = Button(pin=Pin(BUTTON_A_PIN, mode=Pin.IN, pull=Pin.PULL_UP), callback=button_a_callback)
button_b = Button(pin=Pin(BUTTON_B_PIN, mode=Pin.IN, pull=Pin.PULL_UP), callback=button_b_callback)
@dentex

This comment has been minimized.

Copy link

@dentex dentex commented Sep 7, 2020

Hi.
IMHO it's more a button "long press" detection than a debounce...
Am I right?

(Also, using IRQ_RISING only, triggers changes to 0 exclusively)

This is my fork: https://gist.github.com/dentex/8035c7d62279ae139e915e7f4f3dbe91

@olegglarin

This comment has been minimized.

Copy link

@olegglarin olegglarin commented Jan 18, 2021

Hi,
What if self.callback function runs longer than the min_ago value, e.g. 300 ms?
Should one increase min_ago accordingly?

In my understanding, it's better to swap lines #35 and #36.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment