前段时间买了一只树莓派来玩,在上面配置了一些文件共享服务、闹钟等功能(这些功能后面会在博客写上),开启闹钟的第一天就发生了一个令人头疼的问题,我用的是 3b+ ,所以装了风扇,一晚上下来无数次被风扇的声音吵醒,第二天就把它关掉了。。。。
树莓派装上风扇后噪音会比较大,而且风扇不停地转动会增加耗电,通过一个三极管配合树莓派的 gpio 接口就可以实现对风扇的控制,像笔记本电脑一样,只有在 cpu 需要降温的时候风扇才会转动。
参考自 树莓派实验室
材料清单
- 树莓派 x1
- 三极管 x1
- 风扇 x1
- 面包板 x1 (可选)
- 杜邦线若干
连线
如图为电路连线图,VCC, GND, GPIO 分别对应树莓派的引脚

如图为树莓派引脚功能图,GPIO 选择树莓派上任意一个 GPIO 接口即可,正负极一定注意别接反了。

驱动代码
依赖库安装
使用下面的代码需首先安装 wiringPi 库。
1
| git clone git://git.drogon.net/wiringPi
|
也可以到 http://wiringpi.com 进行下载
控制风扇的代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25
|
import commands,time
FAN_GPIO = 15 commands.getoutput('sudo gpio mode ' + str(FAN_GPIO) + ' out' )
while True: tmpFile = open('/sys/class/thermal/thermal_zone0/temp') cpu_temp_raw = tmpFile.read() tmpFile.close() cpu_temp = round(float(cpu_temp_raw) / 1000, 1) print cpu_temp
if cpu_temp >= 50.0 : commands.getoutput('sudo gpio write ' + str(FAN_GPIO) + ' 0'); if cpu_temp <= 45.0 : commands.getoutput('sudo gpio write ' + str(FAN_GPIO) + ' 1');
time.sleep(10)
|
配置开机启动
我使用了配置服务的方式实现的开机启动
在 /etc/init.d/
下新建文件 temp_ctrl
并给上执行权限
文件内容如下
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| #!/bin/bash
case "$1" in start) echo "start temp ctrl" nohup /home/pi/gpio/fenshan.py & ;; stop) echo "stop temp ctrl" kill $(ps aux | grep -m 1 'python /home/pi/gpio/fenshan.py' | awk '{ print $2 }') ;; *) echo "Usage : service temp-ctrl start/stop" exit 1 ;; esac exit 0
|
在 /etc/rc.local
中 exit 0
之前添加一行
1 2 3
| /etc/init.d/temp_ctrl start
exit 0
|
最终效果
程序执行的效果

通过服务的方式开启与关闭

连线实物图
