今日目標
在完成了前三天的智慧倒車雷達、智慧溫室與節能路燈後,今天我們要實作第四個極具實用性與趣味性的物聯網綜合應用——防盜密碼門禁系統。
今天我們將結合Push Button實體按鈕、SSD1306 OLED螢幕,以及蜂鳴器。透過3個實體按鈕輸入特定組合密碼在 OLED 上即時呈現星號(*)、輸入狀態、解鎖成功或密碼錯誤的動畫與聲光提示。
程式碼
import time
from machine import Pin, I2C, PWM
import ssd1306
i2c = I2C(0, scl=Pin(22), sda=Pin(21), freq=400000)
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
btn_a = Pin(4, Pin.IN, Pin.PULL_UP)
btn_b = Pin(5, Pin.IN, Pin.PULL_UP)
btn_c = Pin(18, Pin.IN, Pin.PULL_UP)
buzzer_pwm = PWM(Pin(19), freq=1000, duty=0)
PASSWORD = ['A', 'B', 'C']
input_buffer = []
def play_tone(freq, duration_ms):
buzzer_pwm.freq(freq)
buzzer_pwm.duty(512)
time.sleep_ms(duration_ms)
buzzer_pwm.duty(0)
def sound_key_click(): play_tone(1200, 40)
def sound_success():
play_tone(1047, 100)
time.sleep_ms(50)
play_tone(1318, 200)
def sound_denied():
play_tone(400, 300)
def draw_ui(status_text="ENTER CODE", stars=""):
oled.fill(0)
oled.text("=== DOOR LOCK ===", 0, 0)
oled.hline(0, 12, 128, 1)
oled.text(status_text, 10, 24)
oled.text(f"Key: {stars}", 20, 42)
oled.hline(0, 56, 128, 1)
oled.show()
print("=== 門禁防盜密碼鎖系統啟動 ===")
draw_ui()
last_press_time = 0
def check_button(pin, key_name):
global last_press_time
now = time.ticks_ms()
if pin.value() == 0 and time.ticks_diff(now, last_press_time) > 200:
last_press_time = now
sound_key_click()
return key_name
return None
while True:
key = check_button(btn_a, 'A') or check_button(btn_b, 'B') or check_button(btn_c, 'C')
if key:
input_buffer.append(key)
stars = "*" * len(input_buffer)
draw_ui("INPUTTING...", stars)
print(f"目前輸入: {input_buffer}")
if len(input_buffer) == len(PASSWORD):
time.sleep_ms(300)
if input_buffer == PASSWORD:
print("✅ 密碼正確,允許進入!")
draw_ui("ACCESS GRANTED", "***")
sound_success()
else:
print("❌ 密碼錯誤,拒絕進入!")
draw_ui("ACCESS DENIED", "ERROR")
sound_denied()
time.sleep(2)
input_buffer.clear()
draw_ui()
time.sleep_ms(20)
心得
今天我們使用狀態機邏輯與組合按鍵,實作出了極具質感的密碼門禁卡鎖。透過聲光提示與視覺UI的整合,體驗到了完整的產品級互動設計。