Skip to content

Instantly share code, notes, and snippets.

@dentex
Forked from jedie/button_test.py
Last active March 5, 2023 12:50
Show Gist options
  • Save dentex/8035c7d62279ae139e915e7f4f3dbe91 to your computer and use it in GitHub Desktop.
Save dentex/8035c7d62279ae139e915e7f4f3dbe91 to your computer and use it in GitHub Desktop.
microPython button irq long-press detection
import time
from micropython import const
from machine import Pin
BUTTON_A_PIN = const(17)
class Button:
def __init__(self, pin, callback, trigger=Pin.IRQ_FALLING | Pin.IRQ_RISING, min_ago=500):
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)
def button_a_callback(pin):
if pin.value() == 0:
print("Button A (%s) LONG PRESSED" % pin)
button_a = Button(pin=Pin(BUTTON_A_PIN, mode=Pin.IN), callback=button_a_callback)
@vowill
Copy link

vowill commented Mar 5, 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