今日目標
昨天我們成功設定SSD1306 OLED顯示器並印出基本文字,今天我們要將它與DHT22溫濕度感測器結合,打造一個不需要連接電腦Serial Monitor,就能獨立在螢幕上顯示即時溫濕度數據的桌面型溫濕度看板。
程式碼
import time
import dht
from machine import Pin,I2C
import ssd1306
i2c=I2C(0,scl=Pin(22),sda=Pin(21),freq=400000)
oled=ssd1306.SSD1306_I2C(128,64,i2c)
dht_sensor=dht.DHT22(Pin(15))
print("=== OLED溫濕度即時看板系統啟動")
while True:
try:
dht_sensor.measure()
temp=dht_sensor.temperature()
hum=dht_sensor.humidity()
oled.fill(0)
oled.text("===ROOM MONITOR===",0,0)
oled.hline(0,12,128,1)
oled.text("Temp:",0,22)
oled.text(f"{temp:.1f}C",56,22)
oled.text("Humi:",0,38)
oled.text(f"{hum:.1f}%",056,38)
oled.hline(0,52,128,1)
oled.text("Status:OK",0,56)
oled.show()
print("【看板更新】溫度:{temp:.1f}°C|濕度:{hum:.1f}%")
expect OSError:
oled.fill(0)
oled.text("===ERROR===",16,16)
oled.text("DHT22 Read Failed",0,36)
oled.show()
print("DHT22感測器讀取失敗!")
time.sleep(2)
心得
今天把感測器數據畫在OLED螢幕上,關鍵技巧在於利用MicroPython的f-string格式化字串將浮點數轉換為乾淨對齊的文字顯示。