With this code I found on the internet and changed a little bit for measuring temperature I cannot write to the log file when the sleep value is more then 1.
The log file is created but stays empty. With sleep value 1 there are no problems.
import subprocess
import logging
import time
from time import sleep, gmtime, strftime
#Read temp from MCP9808 sensor (Using SPI interface)
import smbus
t_reg = 0x05
address = 0x18
bus = smbus.SMBus(1) # change to 0 for older RPi revision
reading = bus.read_i2c_block_data(address, t_reg)
# t = (reading[0] <:<: 8) + reading[1]
t = (reading[0] << 8) + reading[1]
#Calculate temperature (see 5.1.3.1 in datasheet)
# temp = t & 0x0FFF
def get_temp():
temp = t & 0x0FFF
temp /= 16.0
return(temp)
# if (t & 0x1000):
if (t & 0x1000):
temp -= 256
# try:
# MCP_Temp='%.1f' % (temp*(9.0/5.0)+32.0) #Converts to Farenheit
# except subprocess.CalledProcessError as e:
# print e
#This will add a timestamp to and temp in a CSV ready format
# output=strftime("%m/%d/%Y %H:%M,") + ',' + str(float(temp))
# print output
with open("cpu_temp.csv", "a") as log:
while True:
temp = get_temp()
log.write("{0},{1}\n".format(strftime("%Y-%m-%d %H:%M:%S"),str(temp)))
# sleep(30)
time.sleep(2)