【发布时间】:2022-01-15 21:11:18
【问题描述】:
我尝试用风扇设置我的树莓派。它应该每 5 分钟记录一次温度,并使用 Python 脚本将其写入 .csv 文件。如果温度高于 52 摄氏度,则应打开 USB 集线器,如果低于该值则将其关闭。现在,我创建了一个小网站,以查看我记录的数据。这是我的问题:正如您在屏幕截图中看到的那样,它有时会告诉我 [HOT] 有时 [OK] 对于相同的值?此外,它不会像希望它分离(超过/低于 52 摄氏度)那样分离数据。
Screenshot from my little website(这只显示我的 .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 文件)
有人不知道,为什么结果会那么奇怪? 问候和非常感谢!
【问题讨论】:
标签: python csv while-loop raspberry-pi temperature