Reading and processing button presses with microcontrollers is a lot harder than one could assume because of the signal noise for which we have hardware and software solutions.
I couldn’t find a performant software solution for ESP8266 running MicroPhython (Wemos D1 mini) so I came up with an idea of listening for a pin change interrupt and starting a fixed “one-shot” timer for 200ms that restarts on every interrupt and triggers the final callback once the timer ends:
from machine import Pin, Timer
# Start or replace a timer for 200ms, and trigger on_pressed.
timer.init(mode=Timer.ONE_SHOT, period=200, callback=on_pressed)
# Register a new hardware timer.
timer = Timer(0)
# Setup the button input pin with a pull-up resistor.
button = Pin(0, Pin.IN, Pin.PULL_UP)
# Register an interrupt on rising button input.
It delays the button press event for 200ms after the last interrupt trigger. There is no way of knowing if you’ve actually released the button so it will most likely trigger another event if the button press lasts for more than 200ms.
Are there better ways of doing this? Please share you ideas in the comments.