需要准备的材料
1.带风扇的散热马甲一块,
2.S8550 三极管一颗
3.母口杜邦线一根
首先从中间剪断风扇的正极,把三级管的发射极和集电极分别接在正极两边,然后拿出杜邦线接到三极管的基极。如下图所示(水平有限将就看看)
然后正极连接树莓派第4脚,负极连接树莓派第6脚,蓝色杜邦线连接树莓派第8脚(如下图)
然后安装python RPi.GPIO库
sudo pip install RPi._GPIO
接下来执行代码就可以了:
sudo python3 rpi-gpio-fan.py
import RPi._GPIO as GPIO
import time
class RaspiFanControl:
def __init__(self):
self.max_temp = 45
self.min_temp = 40
self.run_time = 600 # 这里是运行时间,达到温度后运行10分钟,再停下来进入下一轮的检测
self.gpio_ping = 14
self.fan_status = 'Stop'
self.temp_path = '/sys/class/thermal/thermal_zone0/temp'
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(self.gpio_ping, GPIO.IN)
def check_cpu_temp(self):
with open(self.temp_path, 'r') as tmp:
cpu_temp = int(tmp.read()) / 1000
if cpu_temp >= self.max_temp:
self.raspi_fan_no(cpu_temp)
elif self.fan_status == "Running":
if cpu_temp <= self.min_temp:
self.raspi_fan_off(cpu_temp)
else:
self.raspi_fan_between(cpu_temp)
def raspi_fan_no(self, cpu_temp):
ping_status = GPIO.input(self.gpio_ping)
if ping_status == 1:
GPIO.setup(self.gpio_ping, GPIO.OUT)
GPIO.output(self.gpio_ping, True)
self.fan_status = 'Running'
print('.' * 40)
print('Current temperature: %s' % cpu_temp)
print('Fan status: %s' % self.fan_status)
print('DateTime: %s' % time.ctime())
print('.' * 40)
time.sleep(self.run_time)
def raspi_fan_off(self, cpu_temp):
if GPIO.input(self.gpio_ping):
GPIO.setup(self.gpio_ping, GPIO.IN)
self.fan_status = 'Stop'
print('.' * 40)
print('Current temperature: %s' % cpu_temp)
print('Fan status: %s' % self.fan_status)
print('DateTime: %s' % time.ctime())
print('.' * 40)
time.sleep(self.run_time)
def raspi_fan_between(self, cpu_temp):
print('.' * 40)
print('Current temperature: %s' % cpu_temp)
print('Fan status: %s' % self.fan_status)
print('DateTime: %s' % time.ctime())
print('.' * 40)
time.sleep(60) # 这里是温度没有达到的话,就每分钟检测一次,
if __name__ == '__main__':
raspi_fan = RaspiFanControl()
while True:
raspi_fan.check_cpu_temp()