Measure CPU temperature of Raspberry Pi with Python

You can get the CPU temperature of Raspberry Pi with vcgencmd measure_temp. I measured 60 times per second for monitoring, and finally displayed the average.

code

The language used is Python 3.7. If you type Python on Raspberry Pi, Python2 will come out by default, but it is not compatible with 3.7, so please be careful not to stare at the error. e? I'm the only one who does that. Yes. If you give execute permission with sudo chmod a + x temp.py and set it to ./temp.py, it will work.

temp.py


#!/usr/bin/python3.7

import subprocess
import time
import sys
import re

num = 60
ave = 0

print(subprocess.run('lsb_release -a', shell=True, encoding='utf-8', stdout=subprocess.PIPE).stdout)

try:
    while num > 0:
        temp = subprocess.run('vcgencmd measure_temp', shell=True, encoding='utf-8', stdout=subprocess.PIPE).stdout.split('=')
        freq = subprocess.run('vcgencmd measure_clock arm', shell=True, encoding='utf-8', stdout=subprocess.PIPE).stdout.split('=')
        volt = subprocess.run('vcgencmd measure_volts', shell=True, encoding='utf-8', stdout=subprocess.PIPE).stdout.split('=')

        temp = temp[1].replace('\n', '')
        freq = int(freq[1].replace('\n', '')) / 1000000000
        volt = volt[1].replace('\n', '')

        print('Temp: ' + temp + ', Freq: ' + f'{freq:.2f}' + 'GHz, Volt: ' + str(volt) + ' (' + str(num) + ')')

        ave += int(re.sub('\\D', '', temp))
        num -= 1
        time.sleep(1)
    print('Average: ' + f'{ave / 600:.1f}' + "'C (60s)")

except KeyboardInterrupt:
    sec = 60 - num
    print(' Aborted.\nAverage: ' + f'{ave / sec / 10:.1f}' + "'C (" + str(sec) + 's)')
    sys.exit()

Where I devised

Please forgive me for the headline that it is a free study during the summer vacation. I researched and wrote various things as a beginner.

version information

~~ I don't really need it, but ~~ First, the Linux version information is displayed. You can display the execution result of your favorite command by rewriting lsb_release -a in print before the loop. I am completely self-satisfied. Subprocess I found that subprocess is good for executing commands from python. I'm not sure why, but I used subprocess because I wanted to wrap it around a long object.

Values other than temperature

Since temperature alone is boring (what), I also displayed the clock frequency and operating voltage. It's quite interesting to see this as an extra. In my environment, I'm not using up to 1.5GHz. KeyboardInterrupt I can get out of the loop with Ctrl + C, but I get an error. Since it is not good for mental health, I enclose the loop processing with try and catch Ctrl + C with ʻexcept Keyboard Interrupt`. By doing this, no error will be spit out, and you can write the processing when exiting.

Other

--You can change the number of seconds to measure by changing the 60 of the variable num. --Put this file in / {hogehoge} and type ln -s / {hogehoge} /temp.py /usr/bin/temp and just type temp in any directory to run this program. You can do it. ――I think there are many unsightly points because it was the first post of a hobby glamor, but please forgive me. --If you are a "professional" glamor, please point out any comments.

Recommended Posts

Measure CPU temperature of Raspberry Pi with Python
Get CPU information of Raspberry Pi with Python
Measure temperature and humidity with Raspberry Pi3 and visualize with Ambient
Let's operate GPIO of Raspberry Pi with Python CGI
Use vl53l0x with Raspberry Pi (python)
I tried running Movidius NCS with python of Raspberry Pi3
Production of temperature control system with Raspberry Pi and ESP32 (1)
Measure and compare temperature with Raspberry Pi and automatically generate graph
Measure SIM signal strength with Raspberry Pi
Detect temperature using python on Raspberry Pi 3!
Working with GPS on Raspberry Pi 3 Python
Notify LINE of body temperature from BLE thermometer with Raspberry Pi # 1
Notify LINE of body temperature from BLE thermometer with Raspberry Pi # 2
Discord bot with python raspberry pi zero with [Notes]
CSV output of pulse data with Raspberry Pi (confirm analog input with python)
I tried L-Chika with Raspberry Pi 4 (Python edition)
[Python + PHP] Make a temperature / humidity / barometric pressure monitor with Raspberry Pi
CSV output of pulse data with Raspberry Pi (CSV output)
Display CPU temperature every 5 seconds on Raspberry Pi 4
Raspberry + am2302 Measure temperature and humidity with temperature and humidity sensor
DigitalSignage with Raspberry Pi
One-liner that outputs 10000 digits of pi with Python
Connect to MySQL with Python on Raspberry Pi
Production of temperature control system with Raspberry Pi and ESP32 (2) Production of transmission device
GPS tracking with Raspberry Pi 4B + BU-353S4 (Python)
Periodically notify the processing status of Raspberry Pi with python → Google Spreadsheet → LINE
Creating a temperature control system with Raspberry Pi and ESP32 (3) Recipient Python file
Record temperature and humidity with systemd on Raspberry Pi
Try debugging Python on Raspberry Pi with Visual Studio.
Take the value of SwitchBot thermo-hygrometer with Raspberry Pi
Log the value of SwitchBot thermo-hygrometer with Raspberry Pi
Ubuntu 20.04 on raspberry pi 4 with OpenCV and use with python
Display USB camera video with Python OpenCV with Raspberry Pi
Simulate temperature measurement with Raspberry Pi + Flask + SQLite + Ajax
Mutter plants with Raspberry Pi
Measure WiFi speed with Python
raspberry pi 1 model b, python
Python beginner opens and closes interlocking camera with Raspberry Pi
Create an LCD (16x2) game with Raspberry Pi and Python
Detect "temperature (using A / D converter)" using python on Raspberry Pi 3!
Run BNO055 python sample code with I2C (Raspberry Pi 3B)
[RaspberryPi] [python] Inform LINE of room temperature with temperature sensor + IFTTT
SSD 1306 OLED can be used with Raspberry Pi + python (Note)
Creating a temperature / humidity monitor with Raspberry Pi (pigpio version)
Connect Raspberry Pi to Alibaba Cloud IoT Platform with Python
Easily make a TweetBot that notifies you of temperature and humidity with Raspberry Pi + DHT11.
[Raspberry Pi] Scraping of web pages that cannot be obtained with python requests + Beautiful Soup
[Raspberry Pi] Stepping motor control with Raspberry Pi
Servo motor control with Raspberry Pi
Serial communication with Raspberry Pi + PySerial
Getting Started with Python Basics of Python
Try L Chika with raspberry pi
10 functions of "language with battery" python
VPN server construction with Raspberry Pi
Try moving 3 servos with Raspberry Pi
Implementation of Dijkstra's algorithm with python
Coexistence of Python2 and 3 with CircleCI (1.0)
Using a webcam with Raspberry Pi
Basic study of OpenCV with Python
Getting Started with Heroku-Viewing Hello World in Python Django with Raspberry PI 3
Control the motor with a motor driver using python on Raspberry Pi 3!