# 匯入所需的模組
from machine import Pin # 從機器模組中匯入引腳和ADC模組
import network # 匯入網路模組
import dht # 匯入DHT感測器模組
import time # 匯入時間模組
import urequests
# 連接到Wi-Fi網路
sta = network.WLAN(network.STA_IF) # 建立Wi-Fi站點(STA)物件
sta.active(True) # 啟用Wi-Fi介面
sta.connect('Wokwi-GUEST', '') # 連接到指定的Wi-Fi網路,請替換成您的Wi-Fi SSID和密碼
print('Linking...')
while not sta.isconnected(): # 等待直到連接成功
pass
print('Link OK')
# 初始化DHT感測器
p0 = Pin(13, Pin.IN)
d = dht.DHT22(p0)
# 初始化變數
make_url = "https://hook.eu2.make.com/8drwr3pfz9tben4avh50bfo31g0svzff"
j = 0
while True:
# 開啟檔案進行寫入
f = open('DHT_Temp.txt', 'w')
Temp = 0
Hum = 0
# 上傳數據之前進行5次測量
try:
for i in range(5):
d.measure()
t = d.temperature()
h = d.humidity()
Temp = Temp + t
Hum = Hum + h
time.sleep(0.5)
except Exception as e:print(e)
# 計算平均溫度和濕度
Temperature = int(Temp / 5)
Humidity = int(Hum / 5)
print("Temperature=", Temperature, "C", "Humidity", Humidity, "%")
# 如果溫度超過25°C,則上傳溫度數據
if (Temperature >= 25):
try:
print(make_url+"?DHT_Temp="+str(Temp))
res = urequests.post(make_url + "?DHT_Temp=" + str(Temperature))
res.close()
print("溫度過高,目前為 " + str(Temperature) + "°C")
except Exception as e:print(e)
# 增加數據計數器
j = j + 1
print('第 ' + str(j) + ' 筆資料已上傳')
# 將數據寫入檔案
f.write(str(Temperature) + ' ' + str(Humidity) + '\n')
# 在進行下一次測量之前等待
time.sleep(5)
# 關閉檔案
f.close()
# from machine import Pin, ADC # 匯入所需的函式庫
# import dht # 引入dht模組,用於操作DHT22溫濕度傳感器
# import time # 引入time模組,用於時間延遲
# import network # 引入network模組,用於連接Wi-Fi
# from umqtt.robust import MQTTClient # 引入MQTTClient模組,用於MQTT通訊
# import urequests # 引入urequests模組,用於發送HTTP請求
# # 連接到 Wi-Fi 網絡
# sta = network.WLAN(network.STA_IF) # 建立Wi-Fi station(STA)物件
# sta.active(True) # 啟用Wi-Fi介面
# sta.connect('Wokwi-GUEST', '') # 連接到指定的Wi-Fi網絡,請替換成你的Wi-Fi SSID和密碼
# print('Linking...') # shell顯示Linking...
# while not sta.isconnected(): # 等待直到連接成功
# pass
# print('Link OK') # shell顯示Link OK
# # 初始化 DHT22 溫濕度傳感器和連接的引腳
# p0 = Pin(13, Pin.IN) # 創建Pin物件,將GPIO13設為資料腳,給定別名為p0,用於連接DHT22溫濕度傳感器
# d = dht.DHT22(p0) # 創建DHT22物件,並指定並指定使用p0物件來連接DHT22溫溼度傳感器
# j = 0 # 初始化計數器
# # 定義 LINE Notify 的 API 網址
# url_line = "https://hook.eu2.make.com/x5of7pptbup4x8koijmkd14ug6diprod"
# while True:
# f = open('DHT_Temp.txt', 'w') # 開啟檔案以寫入數據
# while True:
# Temperature = 0 # 初始化溫度變數
# Humidity = 0 # 初始化濕度變數
# for i in range(5): # 迭代5次以取得平均數值
# d.measure() # 讀取 DHT22 溫濕度傳感器數據
# t = d.temperature() # 讀取溫度值
# h = d.humidity() # 讀取濕度值
# Temperature += t # 累加溫度值
# Humidity += h # 累加濕度值
# time.sleep(3) # 延遲3秒
# Temperature = int(Temperature / 5) # 計算平均溫度
# Humidity = int(Humidity / 5) # 計算平均濕度
# if Temperature >= 25: # 如果溫度超過25度
# urequests.get(url_line + "?value1=" + str(Temperature)) # 發送HTTP請求到LINE Notify
# print("溫度過高,目前為 " + str(Temperature) + "°C") # shell顯示警告訊息
# j += 1 # 計數器加1
# print('第 ' + str(j) + ' 筆資料已上傳') # shell顯示資料上傳狀況
# f.write(str(Temperature) + ' ' + str(Humidity) + '\n') # 寫入溫濕度數據到檔案
# time.sleep(5) # 延遲5秒
# break # 跳出內層迴圈
# f.close() # 關閉檔案