At the first run python script nothing is written to the log file "cpu_temp.csv". When I run the second time then the data is written to the log file. The script is to extract the temperature from the temperature sensor MCP9808. I know the data is first written to "w1_slave" under the folder "/sys/bus/w1/devices/28-0115a4f575ff". The data for the log file are read always from this file. Can someone help me forwarding such that at the first startup script the data read from the sensor is written to the log file? I want the script started via cron. But since the first run doesn't work nothing has been logged.

Python script for reading data from MCP98808 and write to log file "cpu_temp.csv"

import subprocess
import logging
import time
from time import sleep, gmtime, strftime
import smbus

#Constant things, that don't change during run.
t_reg = 0x05
address = 0x18
bus = smbus.SMBus(1) # change to 0 for older RPi revision

def get_temp():
    #The reading variable changes every time you run get_temp()
    reading = bus.read_i2c_block_data(address, t_reg)
    t = (reading[0] << 8) + reading[1]
    temp = t & 0x0FFF
    temp /=  16.0
    if (t & 0x1000):
      temp -= 256

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

Output file cpu_temp.csv

2017-02-04 15:15:38,22.1875
2017-02-04 15:15:48,22.125
2017-02-04 15:15:58,22.125
2017-02-04 15:16:08,22.125
2017-02-04 15:16:18,22.125
  • You should use an absolute path (/home/pi/cpu_temp.csv or whatever) for the log file. I don't know where you are assuming it is going to end up when run via cron, but very possibly it isn't where you think, and this is just plain a bad practice. – goldilocks Feb 4 '17 at 16:25
  • I have tried but no luck. – Lowieke Feb 5 '17 at 16:06

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.