from machine import Pin
import network
import urequests
import ujson
import time
# === Wi-Fi 設定 ===
sta = network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST', '') # 連接 Wokwi 提供的 Wi-Fi 熱點
while not sta.isconnected():
print(".", end="")
time.sleep(0.1)
print("✅ Wi-Fi 連接成功")
# === LED 設定 ===
led_red = Pin(32, Pin.OUT) # 紅色 LED 接 GPIO33
led_yellow = Pin(33, Pin.OUT) # 黃色 LED 接 GPIO32
# === ThingSpeak 設定 ===
Read_host = "http://api.thingspeak.com/channels/"
Read_ChannelID = " 2920727" # 請替換成您的 Channel ID
Read_API_Keys = "05APZZS2PFVRBW6G" # 請替換成您的 Read API Key
# === 環境感測與警報器功能 ===
def check_sensor_data():
# 向 ThingSpeak 查詢最新的溫濕度資料
url = f'{Read_host}{Read_ChannelID}/feeds/last.json?api_key={Read_API_Keys}'
response = urequests.get(url)
sensor_data = ujson.loads(response.text) # 解析 JSON 格式的資料
temperature = sensor_data['field2'] # 取得溫度數據
humidity = sensor_data['field3'] # 取得濕度數據
# 顯示在 Shell 上
print(f"Temperature: {temperature} °C, Humidity: {humidity} %")
# 溫度警報器
if float(temperature) > 45 or float(temperature) < 15:
led_red.value(1) # 開啟紅色 LED
else:
led_red.value(0) # 關閉紅色 LED
# 濕度警報器
if float(humidity) > 55:
led_yellow.value(1) # 開啟黃色 LED
else:
led_yellow.value(0) # 關閉黃色 LED
# === 主程式循環 ===
while True:
check_sensor_data() # 查詢並處理感測器資料
time.sleep(5) # 每 5 秒查詢一次資料