Close

Button Handler Class in Micropython

danjovicdanjovic wrote 08/13/2024 at 16:23 • 3 min read • Like

This Micropython class handles a single button and provides two possible events: Pulse and Long press. It also provides debouncing.

The .event( ) method shall be called at every execution cycle. The constants for debouncing and Long Press thresholds must be proportional to the timing desired. In the example the function is called every 5 ms. Any pulse that lasts less than 50ms is considered as a bounce and hence discarded. If the button is held for more than 500ms the function returns a single LONG press event.

Finally, if the button is pulsed within a time 50ms< t < 100ms the function returns a PULSE 

The function can be experimented here :  https://wokwi.com/projects/406121126820955137

from machine import Pin, 
import time


print("Button Handler Class")

class buttonHandler:
    def __init__(self,pin):
        self.pin = Pin (pin, Pin.IN, Pin.PULL_UP)
        self.tOn = 0
        self.tmp = 0
        self.evnt = None 
    
    def event(self):
        if self.pin():
            if (self.tOn <10):    # does the key get pressed for at least 10 scans ?
                self.tOn=0        # no, it was just a bounce, ignore
                return None                
            else:    
                self.tmp=self.tOn  # yes, save amount of scans 
                self.tOn = 0       # and reset counter           
                
                if (self.tmp < 100): # does the key get pressed for less than 100 scans ?
                    return 1         # yes, it was a pulse
        else:
            if (self.tOn < 500):
                self.tOn = self.tOn + 1  # restrict max value, just in case
                if self.tOn == 100:
                    return 2 # return long only once
            return None


b = buttonHandler (12)   # instantiate and init pin


while 1:
    bte = b.event()
    if (bte):
        if (bte==1):
            print ("short")
        elif (bte==2):
            print ("long")    

            
    time.sleep_ms(5)
Like

Discussions