Toggle Navigation
Hatchery
Eggs
fiee planner
betterbutton.py
Users
Badges
Login
Register
MCH2022 badge?
go to mch2022.badge.team
betterbutton.py
raw
Content
""" # Author: Duality/Robert # email: robertvdtuuk@gmail.com metadata.json = {"name":"Better Buttons","description":"This library has better button support and has several features\r\n\r\nincluding double clicking on a button\r\nlong pressing a button.\r\n\r\ndetecting presses and releases on buttons.","category":"hardware","author":"Robert van der Tuuk","revision":1} """ import buttons import utime class Button(object): def __init__(self, buttonmask, longPressInterval = 3000, doubleClickInterval = 300): self.buttonmask = buttonmask self.previousState = False self.state = 0 self.pressedState = False self.releasedState = False self.longPressStart = 0 self.longPressEnd = 0 self.longPressInterval = longPressInterval self.longPressState = False self.longPressedState = False self.previousDoubleClickTime = 0 self.doubleClickInterval = doubleClickInterval self.doubleClickState = False def checkButton(self): state = buttons.read(self.buttonmask) # get the current button state from the hardware if (state & self.buttonmask) == self.buttonmask: self.pressedState = True else: self.pressedState = False # the button is released but previously was pressed. if self.pressedState == False and self.previousState == True: self.releasedState = True # the button is pressed but previously wasn't pressed. if self.pressedState == True and self.previousState == False: self.longPressEnd = utime.time_ms() + self.longPressInterval self.longPressState = True self.longPressedState = False if utime.time_ms() - self.previousDoubleClickTime < self.doubleClickInterval: self.doubleClickState = True self.previousDoubleClickTime = utime.time_ms() if self.longPressState == True: if(utime.time_ms() - self.longPressEnd >= self.longPressInterval): self.longPressState = False self.longPressedState = True self.previousState = self.pressedState def pressed(self): return self.pressedState def released(self): releasedState = self.releasedState self.releasedState = 0 return releasedState def longPressed(self): longpressed = self.longPressedState self.longPressedState = False return longpressed def doubleClicked(self): doubleClickState = self.doubleClickState self.doubleClickState = False return doubleClickState