from machine import Pin, ADC # 從 machine 模組中導入 Pin 和 ADC
import dht # 導入 DHT 模組,用於讀取 DHT 感測器的數據
import time # 導入 time 模組,用於時間相關功能
import urequests # 導入 urequests 模組,用於進行 HTTP 請求
import network # 導入 network 模組,用於處理網路相關功能
sta = network.WLAN(network.STA_IF) # 連接到 Wi-Fi 網路
sta.active(True) # 啟用網路介面
sta.connect('Wokwi-GUEST','') # 連接到指定的 Wi-Fi 網路
while not sta.isconnected(): # 等待連接成功
pass
adc = ADC(3) # 使用ADC1_3引腳
d = dht.DHT22(Pin(20)) # DHT22連接到引腳20
led_temp = Pin(16, Pin.OUT) # 紅色LED連接到引腳16
led_hum = Pin(15, Pin.OUT) # 黃色LED連接到引腳15
led_adc = Pin(14, Pin.OUT) # 綠色LED連接到引腳14
host='http://api.thingspeak.com' # ThingSpeak 伺服器的主機地址
api_key = 'HORJ3DBYVY42FEAL' #自己的Write API
def read_sensor_data(): # 讀取感測器數據的函式
adc_voltage = adc.read() * 3.3 / 4095 # 將0~4095的ADC值轉換為0~3.3V的電壓值
d.measure() # 進行一次溫濕度的測量
temperature = d.temperature() # 讀取溫度值
humidity = d.humidity() # 讀取濕度值
time.sleep(16) # 每 16 秒抓取一次數據
return adc_voltage, temperature, humidity # 函式返回平均電壓、平均溫度和平均濕度的值
while True: # 主程式迴圈
adc_voltage, temperature, humidity = read_sensor_data() # 讀取感測器數據並控制 LED
print("ADC Voltage:", adc_voltage, "V") # 在 shell 上顯示電壓值
print("Temperature:", temperature, "°C") # 在 shell 上顯示溫度值
print("Humidity:", humidity, "%") # 在 shell 上顯示濕度值
led_adc.value(adc_voltage < 1.25) # ADC電壓低於1.25V時LED_ADC亮起
led_temp.value(temperature > 40) # 溫度高於40度時LED_Temp亮起
led_hum.value(humidity > 60) # 濕度高於60%,則 led_hum 亮起
url = '%s/update?api_key=%s&field2=%s&field3=%s' % (host, api_key, str(temperature), str(humidity)) # 準備上傳到 ThingSpeak 的 URL
response = urequests.get(url) # 使用 GET 請求上傳數據到 ThingSpeak
print("Uploaded to ThingSpeak:", response.text) # 在 shell 上顯示上傳狀態