我正在测量Raspberry Pi 3中的CPU温度并获得非常嘈杂的值。 每秒测量一次温度,应通过移动平均值(又称滑动窗口)。每5秒钟应将一个新的Temp.value放入SQLite数据库。 到目前为止,我已经找到了仅适用于静态数据阵列的解决方案。有人可以帮忙解决这个问题吗?我需要一个每秒获取一个值并每5秒返回一次平均值的函数。 然后可以将算法应用于诸如湿度,电压等的值。 Raspberry Pi 3中的温度传感器的精度为0.538°C。
这就是我现在所拥有的:
#!/usr/bin/python
# -*- coding: utf-8 -*-
# Das Programm speist Temperaturen von CPU ins SQLite Datenbank für spätere
# Darstellung auf einer Webseite
from subprocess import check_output
import sqlite3
import time
import numpy
# Pfad zur Datenbank
dbname = "/var/www/cpuTemp_Database.db"
temp_array = []
def log_temperature(currentTemp):
""" Speichern in die Datenbank"""
myConnection = sqlite3.connect(dbname)
myCursor = myConnection.cursor()
myCursor.execute("INSERT INTO temps VALUES (datetime('now', 'localtime'), (?))", (currentTemp,))
myConnection.commit()
myConnection.close()
def abfrage():
""" Macht CPU-Temperaturabfrage und gibt das Wert zurück wie 53.692 """
output = check_output(['cat', '/sys/class/thermal/thermal_zone0/temp'])
stripedVal = output.strip()
tempVal = float(stripedVal)/1000
return tempVal
def main():
""" Main Function"""
while True:
for i in range(5):
tempValue = abfrage()
temp_array.append(tempValue)
time.sleep(1)
meanTemp = numpy.median(temp_array)
log_temperature(meanTemp)
temp_array [:] = []
if __name__ == "__main__":
main()
Greerings,Alex
答案 0 :(得分:1)
我认为你要求的是每5秒获得最后5秒的平均读数,这不是真正的移动平均线。这应该会给你这种行为。
import numpy
# Once you input enough new data points into this function, it will calculate
# and log the average of the last several data points.
def log_periodic_average(new_data_point, window, frequency):
window.append(new_data_point)
if (len(window) >= frequency): # Now is the only time we calculate an average
average = numpy.mean(window)
log_temperature(average) # Using your function to save the average
window = [] # Clear window to collect the next 5 seconds of data
return window
window = []
while True:
point = abfrage() # using your function to get current temperature
window = log_periodic_average(point, window, 5)
sleep(1000)