Last active
December 30, 2021 21:48
-
-
Save awonak/a8142aa0b7e1d38952e3675a34f27448 to your computer and use it in GitHub Desktop.
Demonstration of an async long press button handler
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Author: Adam Wonak | |
# Copyright Adam Wonak 2021 Released under the MIT license | |
# Created 2021-09-04 | |
""" | |
Demonstrate use of Pushbutton class and long press behavior. | |
Initializing the Pushbutton class will kick off buttoncheck in an infinite | |
async loop in a thread. The Pushbutton handlers press, release, and long | |
will print their name when triggered. | |
Main program prints a "." once per second while program.run is True. Long | |
press will toggle program's run state. | |
""" | |
from machine import Pin | |
import uasyncio as asyncio | |
from button import Pushbutton | |
class Program: | |
run = True | |
def toggle(self): | |
self.run = not self.run | |
async def start(self): | |
while True: | |
if self.run: | |
print(".") | |
await asyncio.sleep_ms(1000) | |
def press(): | |
print("PRESS") | |
def release(): | |
print("RELEASE") | |
def long(program): | |
print("LONG") | |
program.toggle() | |
# Set up the program | |
program = Program() | |
# Set up the button | |
pin = Pin(18, Pin.IN, Pin.PULL_UP) | |
button = Pushbutton(pin) | |
button.press_func(press) | |
button.release_func(release) | |
button.long_func(long, (program,)) | |
# Main program function | |
async def main(): | |
loop = asyncio.get_event_loop() | |
loop.create_task(program.start()) | |
loop.run_forever() | |
try: | |
asyncio.run(main()) | |
finally: | |
asyncio.new_event_loop() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment