Micropython Asyncio example
import uasyncio as asyncio | |
from machine import Pin, PWM | |
from encoder import Encoder | |
from time import sleep_us, sleep_ms | |
button = Pin(14, Pin.IN, Pin.PULL_UP) | |
class LedStripController: | |
def __init__(self, enc, pwm): | |
self.encoder = enc | |
self.led_pwm = pwm | |
self.to_brightness = 0 # Percentage brightness. 0 = off | |
self.on = False # State of the LED strip | |
self.pressed = False # Has the button been pressed? | |
async def switch_loop(self): | |
while True: | |
if self.pressed: | |
self.to_brightness = 0 if self.on else 100 | |
await asyncio.sleep_ms(50) # Debounce | |
self.pressed = False | |
self.on = not self.on | |
print('Button pushed, {}'.format(self.on)) | |
await asyncio.sleep_ms(100) | |
async def encoder_loop(self): | |
while True: | |
val = self.encoder.value | |
self.encoder.cur_accel = max(0, self.encoder.cur_accel - self.encoder.accel) | |
if self.to_brightness != val: | |
print(val) | |
self.to_brightness = val | |
await asyncio.sleep_ms(100) | |
def press_button(self, _): | |
self.pressed = True | |
def main(enc): | |
global button | |
pwm = PWM(Pin(15)) | |
controller = LedStripController(enc, pwm) | |
button.irq(trigger=Pin.IRQ_FALLING, handler=controller.press_button) | |
loop = asyncio.get_event_loop() | |
loop.create_task(controller.switch_loop()) | |
#loop.create_task(encoder_loop(enc)) | |
#try: | |
loop.run_until_complete(controller.encoder_loop()) | |
#except: | |
# enc.close() | |
enc = Encoder(pin_clk=13, pin_dt=12, pin_mode=Pin.PULL_UP, | |
min_val=4, max_val=100, clicks=1, accel=2) | |
enc._value = 100 | |
main(enc) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment