要將程式改為每15分鐘根據時間比對發送資料,你可以使用time.time()來取得當前時間,並進行時間差的計算。每當與上一次發送資料的時間相差15分鐘(900秒)時,發送一次資料。
以下是改寫的程式碼:
python
複製程式碼
import urequests
import network
import dht
from machine import Pin
import time
# Wi-Fi 設定
SSID = 'your_SSID'
PASSWORD = 'your_PASSWORD'
SERVER_URL = 'http://your_server_ip/data' # 替換為伺服器的IP地址
# 連接 Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF) # STA_IF表示Station模式
wlan.active(True)
wlan.connect(SSID, PASSWORD)
while not wlan.isconnected():
print('Connecting to WiFi...')
time.sleep(1)
print('Connected to WiFi', wlan.ifconfig())
# 初始化DHT感測器 (以DHT11為例)
sensor = dht.DHT11(Pin(4)) # DHT感測器接在GPIO4
# 發送資料
def send_data():
try:
# 測量溫度與濕度
sensor.measure()
temperature = sensor.temperature() # 攝氏溫度
humidity = sensor.humidity() # 濕度
# 構建發送的數據
data = {
"name": "ESP32_1", # 此ESP32的名稱
"ip": wlan.ifconfig()[0], # ESP32的IP
"temperature": temperature, # 溫度
"humidity": humidity, # 濕度
"timestamp": time.time() # 當前時間戳
}
# 發送POST請求
headers = {'Content-Type': 'application/json'}
response = urequests.post(SERVER_URL, json=data, headers=headers)
print('Data sent:', response.text)
response.close()
except Exception as e:
print('Failed to send data:', e)
# 主程序
connect_wifi()
# 記錄上次發送資料的時間
last_sent_time = time.time()
# 每15分鐘發送一次資料
while True:
current_time = time.time()
# 檢查當前時間與上次發送時間的差異是否超過15分鐘(900秒)
if current_time - last_sent_time >= 900:
send_data()
last_sent_time = current_time # 更新上次發送時間
# 短暫延遲,避免程式過度佔用CPU
time.sleep(1)
時間記錄與比對: 我們在程式啟動後記錄第一次發送資料的時間 last_sent_time = time.time(),然後在每個迴圈中透過 time.time() 取得當前時間,計算當前時間與上次發送時間的差異。如果時間差超過900秒(即15分鐘),則發送資料並更新 last_sent_time。
時間條件判斷: 利用 if current_time - last_sent_time >= 900: 來檢查是否已經過了15分鐘。滿足條件後發送一次資料,並更新 last_sent_time。
短暫延遲: 在 while 迴圈中增加了 time.sleep(1),這樣可以避免迴圈頻繁執行佔用過多的CPU資源。這樣每秒鐘會檢查一次時間是否到了發送資料的時間。