0%

树莓派实现温控风扇

树莓派风扇声音太大了, 非常影响睡觉, 不开风扇cpu温度又很容易太高了

准备

  • 杜邦线母对母2根, 公对母2根, 直接淘宝买40pin的2排
  • 三极管S85501个,淘宝买2块钱50个包邮
    • S8550为PNP型三极管,基极施加低电平时才导通电路,如果是用的NPN型三极管则与之相反
  • 树莓派小风扇1个

树莓派引脚:

三极管引脚:

  • E: 发射机
    • 正级(接电源正极, 5V)
    • 可接树莓派4号引脚
  • B: 基级
    • 信号极控制是否通电(GPIO)
    • 可以接树莓派8号引脚
  • C:集电极
    • 负极 (接电源负极, Ground)
    • 可以接树莓派6号引脚

接线

  1. 风扇红线(正极)接树莓派5V,如4号引脚
  2. 风扇黑线(负极)接三极管C(集电集)
  3. 三极管E(发射极)接树莓派Ground, 如6号引脚
  4. 三极管B级, 接树莓派GPIO,如8号引脚

如图:

Python程序风扇

在python交互式命令行下测试下是否可行

1
2
3
4
5
6
7
8
9
10
11
12
13
pi@raspberrypi:~/script $ python
Python 2.7.16 (default, Apr 6 2019, 01:42:57)
[GCC 8.2.0] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import RPi.GPIO as GPIO
>>> GPIO_OUT = 14
>>> GPIO.setmode(GPIO.BCM)
>>> GPIO.setwarnings(False)
>>> GPIO.setup(GPIO_OUT, GPIO.OUT, initial=GPIO.HIGH)
>>> GPIO.output(GPIO_OUT, GPIO.LOW) # 风扇开
>>> GPIO.output(GPIO_OUT, GPIO.HIGH) # 风扇关闭

注:PNP型三极管GPIO.LOW是开, HIGH是关, NPN型相反

完整程序:

smartfan.py

主要逻辑:

  1. 读取/sys/class/thermal/thermal_zone0/temp内容, 除1000获取CPU温度
  2. 风扇初始状态设置为关闭状态
  3. 温度低于55度且当前处于关闭状态开机风扇
  4. 温度低于45度且当前处于开启状态关闭风扇
  5. 每隔15秒查一下温度并更新状态
1
2
mkdir -p /home/pi/script && cd /home/pi/script
wget https://raw.githubusercontent.com/lovehhf/raspi_script/master/smartfan.py

supervisor管理python进程

添加配置文件: vim /etc/supervisor/conf.d/fan.conf:
内容如下:

1
2
3
4
5
6
7
8
[program:fan]
command=/usr/bin/python3 /home/pi/script/smartfan.py
user=root
directory=/home/pi/script
stdout_logfile=/var/log/supervisor/%(program_name)s-stdout.log
stderr_logfile=/var/log/supervisor/%(program_name)s-stderr.log
autorestart=true
autostart=true

重启supervisor并查看状态:

1
2
3
pi@raspberrypi:/var/log $ sudo systemctl restart supervisor
pi@raspberrypi:/var/log $ sudo supervisorctl status fan
fan RUNNING pid 3903, uptime 0:01:26

测试

1
2
3
sudo apt install stress
stress -c 50 # cpu压力测试, 开50个进程不停地sqrt, 一下子风扇就转起来了
tail -f /var/log/fan_control.log # 查看日志

参考链接: