树莓派4 PWM控制风扇转速

5V风扇是笔记本拆下来的,接了个ss8550 NPN三极管。

接线:

pi 5V --- 风扇5V

风扇GND --- 三接管C极

pi BCM 18 --- 三极管B极

pi GND --- 三极管E极

效果图:

树莓派4 PWM控制风扇转速_第1张图片

代码:

 

#!/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)

 

你可能感兴趣的:(树莓派)