ラズパイ ライフを楽しんでますでしょうか。
コロナ過前に入手したので、4年ぐらい前ですかね。
品薄になる直前に入手した Raspberry PI 4 8GB を持っています。
最近、特に利用目的が無くなってきたので、TVサーバーにでもしようかと思ったのですが、熱対策しないと暴走しちゃいますよね。
なので、ファンを取り付けて対策をすることにしました。
で、こんなFanを買って、取り付け(両面テープで)ました。

ピンアサインは、↑こんな感じです。
物が手に入ったので、制御プログラムの作成ですよ。
今回は、Ubuntu23用です。
まず、必要そうな物をrootでぶち込みます。
apt install python-dev-is-python3
apt install python3-pip
apt install python3-rpi.gpio
apt install python3-pigpio
apt install pigpio-tools
pigpio(ラズパイでGPIOを制御するやつ)ってのが、Ubuntuでパッケージ化されていなかったので、ビルドです。
ビルドに必要そうな物は、適当にぶち込んでおいてください。
wget https://github.com/joan2937/pigpio/archive/refs/tags/v79.tar.gz
tar -xvf ./v79.tar.gz
cd pigpio-79
make
make install
#define PI_DEFAULT_SOCKET_PORT 8888
#define PI_DEFAULT_SOCKET_PORT_STR "8888"
#define PI_DEFAULT_SOCKET_PORT 8898
#define PI_DEFAULT_SOCKET_PORT_STR "8898"
pigpio.py
port = os.getenv("PIGPIO_PORT", 8888),
port = os.getenv("PIGPIO_PORT", 8898),
[Unit]Description=Daemon required to control GPIO pins via pigpio[Service]#ExecStart=/usr/local/bin/pigpiod -l -m #Disable alertsExecStart=/usr/local/bin/pigpiod -m #Disable alertsExecStop=/bin/systemctl kill pigpiodType=forking[Install]WantedBy=multi-user.targetsystemctl daemon-reload
systemctl enable pigpiod
systemctl restart pigpiod
ファン制御用のスクリプトを作っちゃいます。
/root/fanctl.py
#!/bin/python3import signalimport pigpioimport time#Fan controldef fanctl(PWMfreq, PWMduty): gpio_pin0 = 18 pi = pigpio.pi() pi.set_mode(gpio_pin0, pigpio.OUTPUT) # GPIO18 pi.hardware_PWM(gpio_pin0, PWMfreq, PWMduty) pi.stop()#Capture CPU Temparaturedef cputemp(): cputemppath = "/sys/class/thermal/thermal_zone0/temp" try: f = open(cputemppath) return int(f.read())/1000 except Exception as e: return None finally: f.close()running = True#Catch signaldef handle_signal(signum, frame): global running print(f"Received signal {signum}. Exiting loop.") running = False# シグナル設定signal.signal(signal.SIGINT, handle_signal)signal.signal(signal.SIGTERM, handle_signal)#Loopwhile(running): ctemp = cputemp() PWMfreq = 2 PWMduty = 500000 if ctemp < 45.0: PWMfreq = 0 PWMduty = 1000000 elif ctemp < 53.0: PWMfreq = 240000 PWMduty = 1000000 else: PWMfreq = 800000 PWMduty = 1000000 print(ctemp) fanctl(PWMfreq,PWMduty) time.sleep(10)
実行権限を与えておきます
chmod a+x /root/fanctl.py
スクリプトもサービスデーモン化しときます。
[Unit]Description=Raspberry Pi Fan ControlAfter=network.target[Service]ExecStart=/usr/bin/python3 /root/fanctl.pyWorkingDirectory=/tmpStandardOutput=file:/var/log/fanctl.logStandardError=file:/var/log/fanctl_error.logRestart=always[Install]WantedBy=multi-user.target
スクリプトも登録して起動だ
systemctl daemon-reload
systemctl enable fanctl
systemctl restart fanctl





