Raspberry Pi 改装自动散热风扇

购买材料

准备

配线

编写软件

1.先执行命令sudo nano fantemp.py,再粘贴以下No.1或No.2的内容; 2.执行命令给文件权限:chmod 777 fantemp.py

No.1

#!/usr/bin/python2
#coding:utf8
#自动风扇控制程序,使用wiringPi的gpio命令来操作GPIO
import commands,time
#控制风扇的GPIO
FAN_GPIO = 21
commands.getoutput('sudo gpio mode '+str(FAN_GPIO)+' OUTPUT')
 
while True:
     # 获取CPU温度
    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
  
    #如果温度大于50`C,就启动风扇
    if cpu_temp >= 50.0 :
        commands.getoutput('sudo gpio write '+str(FAN_GPIO)+' 0')
    #如果温度小于45`C,就关闭风扇
    if cpu_temp <= 45.0 :
        commands.getoutput('sudo gpio write '+str(FAN_GPIO)+' 1')
     
    time.sleep(0.5)

No.2

import sys
import time
try:
    import RPi.GPIO as GPIO
except RuntimeError:
    print("Error importing RPi.GPIO!  This is probably because you need superuser privileges.  You can achieve this by using 'sudo' to run your script")


def cpu_temp():
    with open("/sys/class/thermal/thermal_zone0/temp", 'r') as f:
        return float(f.read())/1000


def main():
    channel = 21
    GPIO.setmode(GPIO.BOARD)
    GPIO.setwarnings(False)

    # close air fan first
    GPIO.setup(channel, GPIO.OUT, initial=GPIO.HIGH)
    is_close = True
    while True:
        temp = cpu_temp()
        if is_close:
            if temp > 45.0:
                print time.ctime(), temp, 'open air fan'
                GPIO.output(channel, GPIO.HIGH)
                is_close = False
        else:
            if temp < 38.0:
                print time.ctime(), temp, 'close air fan'
                GPIO.output(channel, GPIO.LOW)
                is_close = True

        time.sleep(0.5)
        print time.ctime(), temp


if __name__ == '__main__':
    main()

添加自启动(通过桌面)

1.在/home/pi/.config/目录下新建一个名为 autostart 的文件夹: mkdir .config/autostart

2.在 autostart 目录下新建fanauto.desktop(经测试名字任意,但后缀必须是.desktop): 执行命令:nano .config/autostart/fanauto.desktop

3.fanauto.desktop文件内容如下(需复制):

[Desktop Entry]

Type=Application

Name=fanauto

NoDisplay=true

Exec=/home/pi/fantemp.py

测试

执行重启命令:sudo reboot

⚠️ 转载请注明原博客地址【https://yanhuiblog.tk】Andy所作,谢谢合作!

打赏一个呗

取消

感谢您的支持,我会继续努力的!🤝

让我们一起加油,一起奋斗!💪

扫码支持
扫码支持
扫码打赏,您说多少就多少,请确认账号信息哦!

支付宝🆔:yanhui5858vip

微信🆔:SINAVIO¹⁸⁶₀₀₂₆⁰³⁵⁹

打开相对的扫一扫,即可进行扫码打赏哦,请确认账号信息哦!