在制作自己的温控风扇前,本人也查阅了网上其他资料,最终选用了三极管方案,可以轻松塞进树莓派的外壳中。全程无焊接,以后不用也可方便拆卸线材、杜邦头、三极管元件等用作其他用途。
准备材料
- 树莓派风扇(买树莓派的时候应该都有配套)
- 三极管S8550
- 杜邦线
第一步 接线
按照图中所示接线
第二步 编写驱动
安装RPi.GPIO模块sudo apt-get install python3-rpi.gpio
附上驱动代码
#!/usr/bin/python3
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 = 14
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
# open air fan first
GPIO.setup(channel, GPIO.OUT, initial=GPIO.LOW)
is_close = False
while True:
temp = cpu_temp()
if is_close == True:
if temp > 50.0:
print (time.ctime(), temp, 'open air fan')
GPIO.output(channel, GPIO.LOW)
is_close = False
else:
if temp < 45.0:
print (time.ctime(), temp, 'close air fan')
GPIO.output(channel, GPIO.HIGH)
is_close = True
time.sleep(15.0)
#print time.ctime(), temp, is_close
if __name__ == '__main__':
main()
新建文件在/usr/local/bin/customCtrl/tempctl.py,将上述代码复制到文件中,保存;
执行nohup python3 -u /usr/local/bin/customCtrl/tempctl.py > /usr/local/bin/customCtrl/tempctl.log 2>&1 &
第三步 开机启动
编辑/etc/rc.local文件sudo vim /etc/rc.local
加入nohup python3 -u /usr/local/bin/customCtrl/tempctl.py > /usr/local/bin/customCtrl/tempctl.log 2>&1 &
:wq
保存
然后重启树莓派,你会发现只有当温度升高的时候,风扇才会转
注意:因为这里使用的三极管为PNP型三极管,基极施加低电平时才导通电路,如果是用的NPN型三极管则与之相反。