import network
import urequests
import time
import random
from machine import Pin
# -------- Wi-Fi 設定 --------
SSID = "Wokwi-GUEST" # "你的WiFi名稱"
PASSWORD = "" # "你的WiFi密碼"
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
time.sleep(0.5)
print('WiFi connected:', wlan.ifconfig())
# -------- Blynk 設定 --------
BLYNK_AUTH = 'XoNXUD1WSva6Jmuj9HPyeBr5Sx8ogbWj' #'你的Blynk Auth Token'
BLYNK_LED_URL = 'http://blynk.cloud/external/api/v1/{}/update/V0?value={}'
BLYNK_TEMP_URL = 'http://blynk.cloud/external/api/v1/{}/update/V1?value={}'
BLYNK_HUMI_URL = 'http://blynk.cloud/external/api/v1/{}/update/V2?value={}'
# -------- 硬體設定 --------
led = Pin(15, Pin.OUT)
# -------- 主程式 --------
while True:
# LED 閃爍並上傳狀態到 Blynk
led.value(1)
try:
urequests.get(BLYNK_LED_URL.format(BLYNK_AUTH, 1))
except Exception as e:
print("LED ON update error:", e)
time.sleep(1)
led.value(0)
try:
urequests.get(BLYNK_LED_URL.format(BLYNK_AUTH, 0))
except Exception as e:
print("LED OFF update error:", e)
time.sleep(1)
# 模擬溫濕度數據
temp = random.randint(20, 35) # 假設攝氏 20~35℃
humi = random.randint(40, 80) # 假設濕度 40~80%
print('Temp:', temp, 'Humi:', humi)
# 上傳隨機數據到 Blynk
try:
urequests.get(BLYNK_TEMP_URL.format(BLYNK_AUTH, temp))
urequests.get(BLYNK_HUMI_URL.format(BLYNK_AUTH, humi))
except Exception as e:
print("Sensor upload error:", e)
time.sleep(2)