Raspberry Pi CPU Temperature with Python

By | October 22, 2018

I use the Python code below to get the temperature of my Raspberry Pi CPU and publish it using Apache. It is a simple block of code that ascertains the temperature of the CPU and writes it, along with the current time, to a text file. Comments in the code provide more details.

#import modules and functions
import time
from gpiozero import CPUTemperature

#create a variable to hold CPU temperature
cpu = CPUTemperature()

#open a file for writing then write the temperature
f = open("/var/www/html/CPUTemp.txt", "w")
f.write(str(cpu))

#create a variable to hold the current time and write it to the open file
localtime = time.asctime(time.localtime(time.time()))
f.write(localtime)

#close the file
f.close()

2 thoughts on “Raspberry Pi CPU Temperature with Python

  1. Ole Hansen-Skovmoes

    Hi

    Thanks for your good work on temperature censoring with raspberry pi.

    You have for some time now read and stored indoor and outdoor temperature using certain censors and the raspberry pi. Is it possible for you to state the reliability of this activity. Over the previous years – how many
    times has it been necessary to exchange the censors and how many times has it been necessary to change the raspberry pi used for registrating temperature? Moreover, how often do you need to check up and adjust the (one) wire connection ind order keep it running?

    / Ole ( from Denmark )

    Reply
    1. Pat Pace Post author

      Thank you for your comment. I have only used these 1-wire sensors for temperature sensing. Reliability is good – I can get the temperature every time I poll the sensor. The indoor sensor is accurate and reads the same as another thermometer. The outdoor sensor reads high in the winter and low in the summer. The wire to both sensors is about 1 meter and it may heat or cool the outdoor sensor depending on the indoor temperature. In other words, the wire to the sensor may transfer heat to the sensor in the winter and cool in the summer.

      I do not adjust the temperature nor have I replaced the sensors but I check them several times a week. I have replaced the Raspberry Pi once after one year of use.

      Reply

Leave a Reply

Your email address will not be published. Required fields are marked *