我嘗試用風扇設定我的樹莓派。它應該每 5 分鐘記錄一次溫度,并使用 Python 腳本將其寫入 .csv 檔案。如果溫度高于 52 攝氏度,則應打開 USB 集線器,如果低于該值則將其關閉。現在,我創建了一個小網站來查看我記錄的資料。這是我的問題:正如您在螢屏截圖中看到的那樣,對于相同的值,它有時會告訴我 [HOT] 有時會 [OK]?此外,它不會像希望它分離(超過/低于 52 攝氏度)那樣分離資料。
我的小網站截圖(僅顯示我的 .csv 檔案)
我的 .py 代碼:
from gpiozero import CPUTemperature
from time import sleep, strftime, time
from datetime import datetime, timedelta
from threading import Timer
import matplotlib.pyplot as plt
v=datetime.today()
w = v.replace(day=v.day, hour=1, minute=0, second=0, microsecond=0) timedelta(days=1)
delta_t=w-v
secs=delta_t.total_seconds()
cpu = CPUTemperature()
plt.ion()
x = []
y = []
def write_tempHot(temp):
with open("/var/www/html/cpuTemp.csv", "a") as log:
log.write("{0}{1}\n".format(strftime("%Y-%m-%d %H:%M:%S = [HOT] "),str(temp)))
def write_tempLow(temp):
with open("/var/www/html/cpuTemp.csv", "a") as log:
log.write("{0}{1}\n".format(strftime("%Y-%m-%d %H:%M:%S = [OK] "),str(temp)))
def clearTemp():
filename = "/var/www/html/cpuTemp.csv"
# opening the file with w mode truncates the file
f = open(filename, "w ")
f.close()
while True:
temp = cpu.temperature
if temp > 52:
temp = cpu.temperature
write_tempHot(temp)
plt.pause(300)
t = Timer(secs, clearTemp)
t.start()
else:
temp = cpu.temperature
write_tempLow(temp)
plt.pause(300)
t = Timer(secs, clearTemp)
t.start()
(也不介意 clearTemp() 函式,我想每天清除一次 .csv 檔案)
有誰不知道,為什么結果那么奇怪?問候和非常感謝!
uj5u.com熱心網友回復:
你的比較是
if temp > 52
什么時候應該
if temp >= 52.0
因為否則您的溫度 Hi 只有在 53C 或以上時才會匹配。
我也會使用time.sleep()而不是plt.pause().
對于你的日志檔案,你有兩個函式可以寫入你的日志檔案,我會用一個來代替:
def write_log(temp):
fmt = """{when} = [{option}] {temp}"""
datefmt = """%Y-%m-%d %H:%M:%S"""
option = "OK"
with open("/var/www/html/cpuTemp.csv", "a") as log:
when = datetime.now().strftime(datefmt)
if temp >= 52.0:
option = "HOT"
log.write(fmt.format(when=when, option=option, temp=temp))
最后,我不明白您為什么要每 5 分鐘截斷一次日志檔案。
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/411742.html
標籤:
