今日目標
在前幾天的實作中,我們都是在while True無限迴圈中不斷檢查按鈕的狀態。這種方法會白白消耗CPU資源,且如果迴圈中有長延遲,按鈕回應就會變到很慢。
今天我們要學習物聯網開發中非常關鍵的技術——中斷。讓CPU平時可以處理其他任務或休息,只有在按鈕被按下的瞬間通知CPU立刻暫停手邊工作並執行指定的函數。
程式碼
import time
from machine import Pin
led_state = False
last_trigger_time = 0
def button_irq_handler(pin):
global led_state, last_trigger_time
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_teigger_time) > 200:
led_state = not led_state
led.value(led_state)
print(f"【硬體中斷觸發!】LED切換為:{'亮' if led_state rlse '滅'}")
last_trigger_time = current_time
button.irq(trigger=Pin.IRQ_FALLING, handler=button_irq_handler)
print("硬體中斷系統已啟動!CPU現在可以安心執行主程式主迴圈…")
system_current = 1
while True:
print(f"主程式背景運行中… 心跳計時:{system_current}秒")
system_current += 1
time.sleep(1)
心得
今天學會了物聯網開發中最經典且高效的中斷控制,與傳統回圈檢查相比,中斷能達到毫秒級的即時回應,同時不會浪費CPU資源。