"""
MicroPython IoT Weather Station Example for Wokwi.com
To view the data:
1. Go to http://www.hivemq.com/demos/websocket-client/
2. Click "Connect"
3. Under Subscriptions, click "Add New Topic Subscription"
4. In the Topic field, type "wokwi-weather" then click "Subscribe"
Now click on the DHT22 sensor in the simulation,
change the temperature/humidity, and you should see
the message appear on the MQTT Broker, in the "Messages" pane.
Copyright (C) 2022, Uri Shaked
https://wokwi.com/arduino/projects/322577683855704658
"""
import network
import time
from machine import Pin
import dht
import ujson
from umqtt.simple import MQTTClient
# MQTT 參數設定
MQTT_CLIENT_ID = "micropython-weather-demo"
MQTT_BROKER = "broker.mqttdashboard.com"
MQTT_TOPIC = "wokwi-weather"
# 硬體初始化
sensor = dht.DHT22(Pin(15))
cooling_system = Pin(14, Pin.OUT) # 設定 GPIO 14 為輸出腳位,模擬降溫風扇
hoting_system = Pin(2, Pin.OUT) # 設定 GPIO 2 為輸出腳位,模擬乾燥設備
# --- WiFi 連線區塊 ---
print("Connecting to WiFi", end="")
sta_if = network.WLAN(network.STA_IF)
sta_if.active(True)
sta_if.connect('Wokwi-GUEST', '')
while not sta_if.isconnected():
print(".", end="")
time.sleep(0.1)
print(" Connected!")
# --- MQTT 初始化 ---
client = MQTTClient(MQTT_CLIENT_ID, MQTT_BROKER)
try:
client.connect()
print("MQTT Connected!")
except:
print("MQTT Initial Connection Failed!")
prev_weather = ""
while True:
try:
# 1. 測量數據
sensor.measure()
t = sensor.temperature()
h = sensor.humidity()
# 2. 在終端機印出目前數值
print("\n[即時監測] 溫度: {}°C, 濕度: {}% ".format(t, h), end="")
# 3. 溫度濕度邏輯判斷 (溫度超過 45 度, 濕度超過60%)
if t > 45:
cooling_system.value(1) # 開啟降溫設備 (輸出高電位)
print("--> 【警告】溫度過高!啟動降溫系統", end="")
else:
cooling_system.value(0) # 關閉降溫設備 (溫度正常)
print("--> 溫度正常", end="")
if h > 60:
hoting_system.value(1) # 開啟乾燥設備 (輸出高電位)
print("--> 【警告】濕度過高!啟動乾燥系統", end="")
else:
hoting_system.value(0) # 關閉乾燥設備 (溫度正常)
print("--> 濕度正常", end="")
# 4. 準備 MQTT 資料
message = ujson.dumps({
"temp": t,
"humidity": h,
})
# 5. 數據傳輸與斷線重連
if message != prev_weather:
try:
client.publish(MQTT_TOPIC, message)
print(" (已同步至雲端)")
prev_weather = message
except Exception as e:
print("\n[錯誤] 傳輸失敗,嘗試重新連線...")
try:
client.connect()
print("重連成功!")
except:
print("伺服器無回應...")
else:
print(" (數據無變動)")
except Exception as sensor_err:
print("\n感測器讀取失敗:", sensor_err)
time.sleep(2) # 每2秒點檢一次