LoginSignup
1
4

More than 3 years have passed since last update.

Raspberry Pi 4 で 5秒ごとにCPUの温度を表示させる

Last updated at Posted at 2020-06-28

はじめに

Rasberry Pi 4 を使っていると結構CPUが熱くなります.
どれくらいCPUが熱くなるのか調べたかったので,Python3を使って5秒ごとにCPUの温度を表示させるプログラムを作ってみました.

環境

OS : Ubuntu server20.04 + Xubuntu Desktop(gdm3)

プログラム

cpu_temperature.py
import time
import threading
import subprocess

def schedule(interval, func, wait = True):
    base_time = time.time()
    next_time = 0
    while True:
        t = threading.Thread(target = func)
        t.start()
        if wait:
            t.join()
        next_time = ((base_time - time.time()) % interval) or interval
        time.sleep(next_time)

def get_cpu_temperature():
    output = subprocess.check_output("cat /sys/class/thermal/thermal_zone0/temp", shell = True, encoding = "UTF-8")
    return int(output) / 1000

def print_cpu_temperature():
    print(get_cpu_temperature())

if __name__ == "__main__":
    schedule(5, print_cpu_temperature)

解説

schedule関数

以下の記事を参考にしました.
Pythonで一定時間ごとに処理を実行する
記事で紹介されているschedule関数のパクリです.
intervalで何秒間隔で実行させたいのか,funcでどの関数を実行させたいのか指定できます.
詳しくはURL先の記事を参照してほしいです.

get_cpu_temperature関数

以下の記事を参考にしました.
RaspberryPi(Raspbian)のCPUの温度をcatを使わないで取得してみた
Pythonからコマンドを実行する
vcgencmdを使った方法でもCPU温度を取得できるみたいですが,今回はその方法を使わずに cat を使って取得することにしました.
cat を使う方法だと1000倍の値で出力されるため,そのまま表示するとわかりづらいです.

LinuxのコマンドをPython3から呼ぶにはいろいろな方法がありますが,今回は cat を使って取得した文字列をPython内で加工したかったのでcheck_output関数を使用することにしました.

check_output関数で cat を使ってCPU温度を取得します.そのままでは1000倍された値なので文字列をint型に直し,1000で割ってreturnさせるような形にしました.
vcgencmdを使う場合はそのままreturnさせても良いと思います.

print_cpu_temperature関数

get_cput_temperature関数で得た値をprintするだけの関数です.
元々schedule関数とget_cpu_temperature関数を使ってグラフを描こうとしたのですが,その前に上2つの関数が正しく動いてくれないと困るので,この関数を作ってみました.

if name == "main"内

5秒間隔でprint_cpu_temperature関数を実行せよ,という意味です.
5の部分を10に変えると10秒間隔になります.

1
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
4