# Fan bang-bang control with pwm import os import time import RPi.GPIO as GPIO # Settings M_TIME = 5 # Measure time interval ON_TEMP = 70 # upper temp value -> Fan turned on OFF_TEMP = 60 # lower temp value -> Fan turned off FAN_PIN = 14 # Transistor for the cooling fan is connected to pin 14 PWM_F = 1000 # PWM frequency in kHz. Change only when fan makes fancy noises DC = 50 # PWM duty cycle for the FAN (0 ... 100, where 100 is the maximum) # setup GPIO GPIO.setwarnings(False) GPIO.setmode(GPIO.BCM) GPIO.setup(FAN_PIN, GPIO.OUT) # Activate PWM on the FAN_PIN p = GPIO.PWM(FAN_PIN, PWM_F) # funtion for reading the cpu temperatur and return it as float def getCPUtemp(): res = os.popen('vcgencmd measure_temp').readline() return (res.replace("temp=", "").replace("'C\n", "")) # main loop for the bang-bang control while True: # get temperature temp_float = float(getCPUtemp()) try: # if actual temp axceeded the upper value, turn fan on if (temp_float > ON_TEMP): p.start(DC) # if actual temp drop below the lower value, turn fan off elif (temp_float < OFF_TEMP): p.stop() except: # for debugging print "ERROR" # cycle time of the control. for temperature it dont have to be fast time.sleep(M_TIME)