Skip to content

Instantly share code, notes, and snippets.

@jedie
Last active January 31, 2024 05:32
Show Gist options
  • Star 11 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save jedie/8564e62b0b8349ff9051d7c5a1312ed7 to your computer and use it in GitHub Desktop.
Save jedie/8564e62b0b8349ff9051d7c5a1312ed7 to your computer and use it in GitHub Desktop.
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
Copy link

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
Copy link

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.

@vowill
Copy link

vowill commented Mar 4, 2023

Unfortunately, the debouncing according to the script above did not work in my application.
So I'm using the "Switch debouncing" instead, as described here.

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