ラズパイのCPU温度を取得する方法

パソコン

※この記事にはプロモーションが含まれています。

ラズパイのCPU温度を取得する方法

はじめに

ラズベリーパイ(Raspberry Pi)は、小型のシングルボードコンピュータであり、多くの人々に愛されています。しかし、長時間の使用や高負荷の処理を行う場合、CPU温度が上昇し、パフォーマンスや安定性に影響を与える可能性があります。そこで、本記事ではラズパイのCPU温度を取得する方法について解説します。

温度の取得方法

ラズパイのCPU温度を取得するためには、vcgencmdコマンドを使用します。このコマンドは、Raspberry PiのGPU制御コマンドであり、様々な情報を取得することができます。

まず、ターミナルを開き、以下のコマンドを実行します。

$ vcgencmd measure_temp

すると、現在のCPU温度が表示されます。例えば、”temp=50.5’C”と表示された場合、CPU温度は50.5℃です。

Pythonスクリプトでの温度取得

Pythonを使用してCPU温度を取得する方法もあります。以下のスクリプトを作成し、実行してみましょう。

import subprocess
def get_cpu_temperature():
    result = subprocess.run(['vcgencmd', 'measure_temp'], capture_output=True, text=True)
    output = result.stdout.strip()
    temperature = output.split('=')[1].split('\'')[0]
    return temperature
cpu_temp = get_cpu_temperature()
print(f"CPU温度: {cpu_temp}℃")

このスクリプトでは、subprocessモジュールを使用してvcgencmdコマンドを実行し、その結果を取得しています。CPU温度は文字列として取得されるため、適切に整形して表示しています。

温度の記録と制限

長時間の使用や高負荷の処理を行う場合、CPU温度が上昇し、パフォーマンスや安定性に影響を与える可能性があります。そのため、CPU温度を定期的に記録し、制限を設けることが重要です。

Pythonを使用してCPU温度を定期的に記録するスクリプトを作成してみましょう。

import subprocess
import datetime
def get_cpu_temperature():
result = subprocess.run(['vcgencmd', 'measure_temp'], capture_output=True, text=True)
output = result.stdout.strip()
temperature = output.split('=')[1].split('\'')[0]
return temperature
def record_temperature():
while True:
current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
cpu_temp = get_cpu_temperature()
with open("temperature_log.txt", "a") as file:
file.write(f"{current_tim

コメント