樹莓派4 PWM控制風扇轉速

5V風扇是筆記本拆下來的,接了個ss8550 NPN三極管。

接線:

pi 5V --- 風扇5V

風扇GND --- 三接管C極

pi BCM 18 --- 三極管B極

pi GND --- 三極管E極

效果圖:

代碼:

 

#!/usr/bin/python3
# encoding: utf-8

import RPi.GPIO
import time
RPi.GPIO.setwarnings(False)
RPi.GPIO.setmode(RPi.GPIO.BCM)
RPi.GPIO.setup(18, RPi.GPIO.OUT)
pwm = RPi.GPIO.PWM(18, 75)

duty = 0
lastDuty = 0

try:
        while True:
            tmpFile = open('/sys/class/thermal/thermal_zone0/temp')
            temp = int(tmpFile.read())
            tmpFile.close()
            duty = 100;
            if temp >= 34500 :
                duty = 60
            if lastDuty >= 36500 :
                duty = 50
            if temp >= 38500:
                duty = 40
            if temp >= 40500:
                duty = 30
            if temp >= 42500:
                duty = 20
            if temp >= 44500:
                duty = 10
            if temp >= 46500:
                duty = 0
            if duty == 100:
                pwm.stop()
                time.sleep(0.2)
                RPi.GPIO.output(18, RPi.GPIO.HIGH)
            if duty == 0:
                pwm.stop()
                time.sleep(0.2)
                RPi.GPIO.output(18, RPi.GPIO.LOW)
            if duty > 0 and duty < 100:
                if lastDuty == 0 or lastDuty == 100:
                    pwm.start(0)
                    time.sleep(1)
                pwm.ChangeDutyCycle(duty)
            lastDuty = duty
            time.sleep(5)
except KeyboardInterrupt:
    pass
pwm.stop()
time.sleep(1)
RPi.GPIO.output(18, RPi.GPIO.LOW)

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章