pythoncsvwhile-loopraspberry-pitemperature

Strange failure while logging CPU-Temp with Python to a .csv-File (Rasbperri-Pi)


i Try to set up my Raspberry pi with a fan. It should log the Temperature every 5 minutes and write it to a .csv-file with a Python Script. If the Temperature is hotter than 52 Degrees Celsius, it shoud turn on a USB-Hub, and turn it of if it is below that value. For now, i created a little website, to see my logged data. And here is my question: as you can see in the screenshot, it tells me sometimes [HOT] and sometimes [OK] for the same Values? Also it is not sepperating the Data like a want it to seperate (over/under 52 Degrees Celsius).

Screenshot from my little website (This only displays my .csv-File)

My .py-code:

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()

(Also dont mind for the clearTemp()-function, i want to clear the .csv-file once a day)

Does anybody have n idea, why the results are that kind of strange? Greetings & Thanks a lot!


Solution

  • Your comparison is

    if temp > 52
    

    when it should be

    if temp >= 52.0
    

    because otherwise your temperature Hi will only match if it is 53C or above.

    I'd also use time.sleep() instead of plt.pause().

    For your logfile, you've got two functions to write to your logfile, I'd use one instead:

    
    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))
    
    

    Finally, I do not understand why you want to truncate your logfile every 5 minutes.