from machine import Pin, ADC
import network
import dht
import time
import urequests
DHTPIN = Pin(14, Pin.IN)
DHT = dht.DHT22(DHTPIN) #溫溼度感測器
LED = Pin(1, Pin.OUT) #警報燈
ADC1 = ADC(4) #水位高度
SW1 = Pin(38, Pin.IN, Pin.PULL_UP)
#ADC電壓偵測
def ADC_Read(ADC_channel):
value = ADC_channel.read()
return value
#按鈕反彈跳偵測
def SW_Scan(sw_name):
if(sw_name.value() == 0):
time.sleep_ms(20)
if(sw_name.value()==0):
while True:
if(sw_name.value()==1):
time.sleep_ms(20)
if(sw_name.value()==1):
break
return 1
return 0
#連線及API設定
sta=network.WLAN(network.STA_IF)
sta.active(True)
sta.connect('Wokwi-GUEST','')
while not sta.isconnected() :
pass
host='http://api.thingspeak.com'
api_key='JBL1XAC70DRE9BAA'
i=0
while True:
h=t=0
adc_value=0
#溫、濕、水位紀錄(紀錄5次)
for n in range(5):
DHT.measure()
t+=DHT.temperature()
h+=DHT.humidity()
adc_value += ADC_Read(ADC1)
#增加按鍵偵測敏感度每10MS做1次偵測(含IF檢測超過3秒體感不出來)
for b in range(300):
if(SW_Scan(SW1)==1):
i+=1
if(i%2==0):
print("Warning disable!!")
LED.value(0)
if(i%2==1):
print("Warning! SW Touched!")
LED.value(1)
time.sleep_ms(10)
#計算溫、濕、水位平均數
t/=5
h/=5
adc_value/=5
#水位換算%數
adc_value = int((adc_value/4095)*100)
print("當前水位", str(adc_value),"%")
#水位警報
if(adc_value<30):
print("Warning! Water level is too low!")
LED.value(1)
elif(adc_value>=30):
LED.value(0)
#資料上傳
url='%s/update?api_key=%s&field1=%s&field2=%s&field3=%s' %(host, api_key, t, h, adc_value)
r=urequests.get(url)
print('response=', r.text)
#避免間隔小於15秒使ThingSpeak不紀錄資料
time.sleep(1)