目的
CoreMP135のLCDにPythonでCPU温度を表示を描画します。
CoreMP135はファンレスであるため、CPU温度があがりやすいので、簡単に確認できるようにしました。
開発環境
Debian12をインストールしたCoreMP135を使いました。
CoreMP135
Description: Debian GNU/Linux 12 (bookworm)
Linux CoreMP135 5.15.118 #1 SMP PREEMPT Thu Jun 27 19:59:30 JST 2024 armv7l GNU/Linux
CPU温度の確認
CoreMP135のCPU温度は、デバイスファイル"/sys/class/thermal/thermal_zone0/temp"で確認することができます。ただし、この値は1000で割る必要があります。
$ cat /sys/class/thermal/thermal_zone0/temp
64164
この場合は、CPU温度64.164℃を表します。
ライブラリのインストール
今回は、Pythonライブラリに、numpy, Pillowを使います。aptコマンドで、numpyとPillowを使します。
sudo apt install python3-numpy
sudo apt install python3-pil
LCDへの描画
温度を取得し、
python3のプログラムで、LCDのフレームバッファ(320x240、RGB565)にCPU温度の画像を書き込みます。
# python3 coremp135_lcd_temp.py
coremp135_lcd_temp.py
import os
import fcntl
import mmap
import time
from PIL import Image, ImageDraw, ImageFont
# フレームバッファのパス
FB_PATH = "/dev/fb1"
# フレームバッファの設定
FB_WIDTH = 320
FB_HEIGHT = 240
def get_cpu_temperature():
with open("/sys/class/thermal/thermal_zone0/temp", "r") as f:
temp = float(f.read()) / 1000.0
return f"{temp:.1f}°C"
def draw_text_to_framebuffer(text):
# 画像を作成
image = Image.new("RGB", (FB_WIDTH, FB_HEIGHT), color="black")
draw = ImageDraw.Draw(image)
# フォントの設定(サイズを大きくする)
font = ImageFont.truetype("/usr/share/fonts/truetype/dejavu/DejaVuSans-Bold.ttf", 48)
# テキストのサイズを取得
bbox = draw.textbbox((0, 0), text, font=font)
text_width = bbox[2] - bbox[0]
text_height = bbox[3] - bbox[1]
# テキストを中央に配置
position = ((FB_WIDTH - text_width) // 2, (FB_HEIGHT - text_height) // 2)
# テキストを描画
draw.text(position, text, font=font, fill="white")
# 画像を180度回転(上下左右反転)
image = image.rotate(180)
# RGB565形式に変換
image_rgb565 = image.convert("RGB")
pixels = image_rgb565.load()
buffer = bytearray(FB_WIDTH * FB_HEIGHT * 2)
for y in range(FB_HEIGHT):
for x in range(FB_WIDTH):
r, g, b = pixels[x, y]
rgb = (r & 0xF8) << 8 | (g & 0xFC) << 3 | b >> 3
buffer[(y * FB_WIDTH + x) * 2] = rgb >> 8
buffer[(y * FB_WIDTH + x) * 2 + 1] = rgb & 0xFF
# フレームバッファに書き込む
with open(FB_PATH, "wb") as fb:
fb.write(buffer)
def main():
while True:
cpu_temp = get_cpu_temperature()
draw_text_to_framebuffer(cpu_temp)
time.sleep(1) # 1秒ごとに更新
if __name__ == "__main__":
main()