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

Leave a Reply

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