2022年3月8日更新
新版本的树莓派系统Raspberry Pi OS自带风扇功能,不再需要手动写入文件的方法了。启用系统自带风扇启停功能如下:

sudo raspi-config #使用root权限进入系统配置
Performance Options #选择第四项,即性能选项
Fan #选择第四项,即风扇
2 #这个数字是三极管的控制引脚,我用的风扇是淘宝买的,默认2;视情况而定
60 #风扇启停的温度,我设置为超过60度时启用风扇

树莓派4B太热了,一直开着风扇主动散热又太吵,就想着加个温控模块,控制风扇根据温度阈值启停。
温控模块自己去淘宝买,十几块钱,就不说哪家了,防止打广告。
新建/etc/fot文件夹,将python脚本命名为fot.py放到其中。将system service命名为fot.service,放到/etc/systemd/system/中。
使用systemctl enable fot设置为开机自启动,使用systemctl start fot实现立即运行脚本。建议关机重启,直接运行可能会因为部内温控模块的不同而存在bug进而无法立即启停风扇。
fot.py

#!/usr/bin/env python3

import RPi.GPIO
import time

start = 60
stop = 50

RPi.GPIO.setwarnings(False)
RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(2, RPi.GPIO.OUT)
pwm = RPi.GPIO.PWM(2,100)
fan = False

try:
    while True:
        with open('/sys/class/thermal/thermal_zone0/temp') as f:
            cur = int(f.read()) / 1000
        if not fan and cur >= start:
            pwm.start(100)
            fan = True
        if fan and cur <= stop:
            pwm.stop()
            fan = False
        time.sleep(1)
except KeyboardInterrupt:
    pwm.stop()

fot.service

[Unit]
Description=Temperature Service
After=multi-user.target

[Service]
WorkingDirectory=/etc/fot
User=root
Type=idle
ExecStart=/usr/bin/python3 /etc/fot/fot.py
Restart=always

[Install]
WantedBy=multi-user.target

标签: linux, 树莓派, raspberry pi

添加新评论