本文章是基于ubuntu的树莓派控制降温风扇,采用python编写,具有开机自启的功能,有很好的降低噪音的功能。其思路是获取cpu温度,并依据不同温度产生不同的pwm来进行控制风扇。具体代码如下:
安装树莓派端口支持库 sudo apt-get install python3-rpi.gpio
import RPi.GPIO as GPIO
import time
FAN=18 #BCM引脚编号
TEMP_MIN=30
TEMP_MAX=50
GPIO.setmode(GPIO.BCM)
GPIO.setup(FAN,GPIO.OUT)
#GPIO.output(FAN,GPIO.HIGH)
GPIO.setwarnings(False)
pwm = GPIO.PWM(FAN, 50)
pwm.start(100)
time.sleep(5)
pwm.stop()
print("风扇防止卡死程序运行结束")
# 设置风扇while True:file = open("/sys/class/thermal/thermal_zone0/temp")# 读取结果,并转换为浮点数temp = float(file.read()) # 关闭文件file.close()print("温度: %.1f" %(temp/1000))if temp<TEMP_MIN*1000:pwm.stop()print("温度低于设定值,风扇关闭")#set_fan(0)#低电平,为开启风扇elif temp>TEMP_MAX*1000:pwm.start(100);print("温度高于最高设定值,风扇全速运行")#set_fan(1)#高电平,为关闭风扇else:dc = (temp - TEMP_MIN * 1000) * 100 / ((TEMP_MAX - TEMP_MIN) * 1000)pwm.start(dc)print("PWM duty cycle:%.1f" %dc)time.sleep(10)#每隔十秒检测一下温度
GPIO.cleanup()
硬件电路图如下:
这里点解电容的作用是为了防止噪音产生的。
最后为了防止树莓派每一次开机都要自己去启动脚本,所以我们设置一下开机自启动。
我这里使用的是supervisor来操作,操作流程如下
- 安装supervisor
sudo apt install supervisor
- 打开配置文件目录
cd /etc/supervisor/conf.d
- 新建配置文件
touch pwmfs.conf
- 编写配置文件内容
vim /etc/supervisor/conf.d/pwmfs.conf
- 配置文件内容如下:
[program:pwmfs]
command = python3 /home/ubuntu/pwmfs.py
autostart = true
注:其中/home/ubuntu/pwmfs.py就是你存放脚本的位置。
- 重启服务
sudo systemctl restart supervisor
- 其他命令
查看supervisor运行状态:sudo supervisorctl status
查看后台进程号:ps -aux|grep pwmfs| grep -v grep