import uasyncio as asyncio
from machine import Pin
# 定義LED和按鈕的引腳號碼
red_led = Pin(23, Pin.OUT)
yellow_led = Pin(21, Pin.OUT)
green_led = Pin(18, Pin.OUT)
red_button = Pin(22, Pin.IN, Pin.PULL_UP)
yellow_button = Pin(19, Pin.IN, Pin.PULL_UP)
green_button = Pin(5, Pin.IN, Pin.PULL_UP)
# 控制LED燈的狀態的函數
async def led_control(pin, duration):
pin.on() # LED燈亮起
await asyncio.sleep(duration) # 程式暫停一段時間
pin.off() # LED燈熄滅
# 處理按鈕事件的函數
async def button_handler(pin, led_task):
while True:
if pin.value() == 0: # 如果按鈕被按下
led_task.cancel() # 停止LED燈的執行
if pin == red_button:
led_task = asyncio.create_task(led_control(red_led, 3))
elif pin == yellow_button:
led_task = asyncio.create_task(led_control(yellow_led, 2))
elif pin == green_button:
led_task = asyncio.create_task(led_control(green_led, 1))
await led_task # 啟動新的LED燈的執行
# 主程式
async def main():
# 創建三個LED燈的任務
red_led_task = asyncio.create_task(led_control(red_led, 0))
yellow_led_task = asyncio.create_task(led_control(yellow_led, 0))
green_led_task = asyncio.create_task(led_control(green_led, 0))
# 為三個按鈕分別創建事件處理任務
red_button_task = asyncio.create_task(button_handler(red_button, red_led_task))
yellow_button_task = asyncio.create_task(button_handler(yellow_button, yellow_led_task))
green_button_task = asyncio.create_task(button_handler(green_button, green_led_task))
# 等待所有任務完成
await asyncio.gather(red_button_task, yellow_button_task, green_button_task)
# 啟動主程式
asyncio.run(main())