import RPi.GPIO as GPIO from time import sleep class Fan: def __init__(self): GPIO.setmode(GPIO.BCM) #prepare switch GPIO port self.switchPin = 22 GPIO.setup(self.switchPin, GPIO.OUT) #prepare PWM GPIO port pwmPin = 27 GPIO.setup(pwmPin, GPIO.OUT) self.pwm = GPIO.PWM(pwmPin, 2000) #Notice: The target frequency for PWM on PC Ventilators is 25kHz. However, the Raspberry Pi 2, I am using for testing, appears not to be able to switch the Pin with that high frequency in a clean manner. But the Fan appears to accept the 2kHz. That might not apply to each and every fan out there. #prepare TACH GPIO port self.tachPin = 17 GPIO.setup(self.tachPin, GPIO.IN) def start(self): GPIO.output(self.switchPin, 1) self.setFullSpeed() def stop(self): GPIO.output(self.switchPin, 0) self.pwm.stop() def setSpeed(self, percent): #some sanity esurance percent = 100 if percent > 100 else percent percent = 0 if percent < 0 else percent #compensation for inverted PWM signal dc = 100 - percent self.pwm.stop() self.pwm.start(dc) def setFullSpeed(self): self.setSpeed(100) def setSlowSpeed(self): self.setSpeed(0) def getSpeed(self): self.rpmCount = 0 GPIO.add_event_detect(self.tachPin, GPIO.RISING, callback=self.rpmCounter) sleep(2) GPIO.remove_event_detect(self.tachPin) pwm = (self.rpmCount/2) * 30 #Notice: The Fan I am using generates two risings per revolution. While many PC-Fans work that way, that again might not apply to every fan. We measure for 2 seconds, means 30 times per minute. return pwm def rpmCounter(self, pin): self.rpmCount += 1 #TESTING PROGRAM print("start Fan") fan = Fan() fan.start() sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("set fan to 75") fan.setSpeed(75) sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("set fan to 50") fan.setSpeed(50) sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("set fan to 25") fan.setSpeed(25) sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("set fan to slow") fan.setSlowSpeed() sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("set fan to full speed") fan.setFullSpeed() sleep(15) print "RPM is {0}".format(fan.getSpeed()) print("stop Fan") fan.stop() GPIO.cleanup()