from machine import Pin
import dht                              #載入所需模組
import time 
import urequests
import network
import ujson
led_wat=Pin(16,Pin.OUT)                 #設定gpio16為adc警示燈(紅燈)
led_temp=Pin(17,Pin.OUT)                 #設定gpio17為hum警示燈(黃燈)
led_hum=Pin(18,Pin.OUT)                #設定gpio18為temp警示燈(綠燈)

#連接wifi
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST')

#等待連接
while not sta.isconnected():
    pass

#ThingSpeak API 相關資訊
host= 'http://api.thingspeak.com/channels/'
ChannelID= '2509498'
api_key= 'RCMMMHODBTVSLNF6'             #Read api key

def get_sensor_data():
    try:
        #取得最新資料
        res=urequests.get("%s%s/feeds/last.json?api_key=%s" % (host, ChannelID, api_key))
        data=ujson.loads(res.text)
        temp=data['field1']
        hum=data['field2']
        wat=data['field3']

        print('')
        print('water level:', wat, '%')  #顯示水位
        print('Temperature:', temp, '°C') #顯示溫度
        print('Humidity:', hum, '%')    #顯示濕度

        if float(wat) < 30:
            led_wat.on()                #點燈
        else:
            led_wat.off()               #熄燈
        if float(temp) < 0:
            led_temp.on()
        else:
            led_temp.off()
        if float(hum) > 65:
            led_hum.on()
        else:
            led_hum.off()
    except:
        print('Error happened')

while True:
    get_sensor_data()                   #讀取感測器資料並顯示
    time.sleep(5)
Loading
esp32-s3-devkitc-1