SLIDE 30 30
Event-Driven Code
import time import micropython from machine import Pin, I2C, Timer import ssd1306 def handle_switch(pin): micropython.schedule(switch_pressed,None) def handle_timer(timer): micropython.schedule(timer_fired,None) def switch_pressed(arg): global count count += 1
- led.fill(0)
- led.text(str(count),0,0)
- led.show()
time.sleep(0.01) # prevent sw bouncing def timer_fired(arg): led.value(1-led.value()) # I/O setup led = Pin(2, Pin.OUT) sw = Pin(0, Pin.IN) i2c = I2C(scl=Pin(4), sda=Pin(5))
- led = ssd1306.SSD1306_I2C(128,64,i2c)
count = 0 # initialize event triggers timer = Timer(0) timer.init( period=500, mode=Timer.PERIODIC, callback=handle_timer) sw.irq( trigger=Pin.IRQ_FALLING, handler=handle_switch) while True: pass
Ideally, CPU should go to sleep here instead of idle loop