Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #!/usr/bin/python
- # -*- coding: utf-8 -*-
- import RPi.GPIO as GPIO
- import time
- import sys
- import os
- import signal
- # Configuration
- FAN_PIN = 14 # BCM pin used to drive transistor's base
- WAIT_TIME = 5 # [s] Time to wait between each refresh
- FAN_LSPD = 20 # [%] Fan minimum speed.
- PWM_FREQ = 25 # [Hz] Change this value if fan has strange behavior
- # Setup GPIO pin
- GPIO.setmode(GPIO.BCM)
- GPIO.setup(FAN_PIN, GPIO.OUT, initial=GPIO.LOW)
- fan=GPIO.PWM(FAN_PIN,PWM_FREQ)
- fan.start(0);
- def getCPUtemperature():
- res = os.popen('/opt/vc/bin/vcgencmd measure_temp').readline()
- temp =(res.replace("temp=","").replace("'C\n",""))
- print("Temp is {0}°C".format(temp)) #Uncomment here for testing
- return temp
- def getTEMP():
- CPU_temp = float(getCPUtemperature())
- return()
- i = 0
- hyst = 1 # Fan speed will change only of the difference of temperature is higher than hysteresis
- tempSteps = [30, 35, 40, 45, 50, 60, 65, 70] # [°C] # Configurable temperature and fan speed steps
- speedSteps = [0, 20, 40, 60, 80, 100, 100, 100] # [%]
- cpuTempOld=0
- fanSpeedOld=0
- # We must set a speed value for each temperature step
- if(len(speedSteps) != len(tempSteps)):
- print("Numbers of temp steps and speed steps are different")
- exit(0)
- try:
- while 1:
- getTEMP()
- time.sleep(5) # Read the temperature every 5 secs
- cpuTempFile=open("/sys/class/thermal/thermal_zone0/temp","r")
- cpuTemp=float(cpuTempFile.read())/1000
- cpuTempFile.close() # Read CPU temperature
- if (abs(cpuTemp-cpuTempOld > hyst)): #Calculate desired fan speed
- if (cpuTemp < tempSteps[0]): # Below first value, fan will run at min speed.
- fanSpeed = speedSteps[0]
- elif(cpuTemp >= tempSteps[len(tempSteps)-1]): # Above last value, fan will run at max speed
- fanSpeed = speedSteps[len(tempSteps)-1]
- else: # If temperature is between 2 steps, fan speed is calculated by linear interpolation
- for i in range(0,len(tempSteps)-1):
- if((cpuTemp >= tempSteps[i]) and (cpuTemp < tempSteps[i+1])):
- fanSpeed = round((speedSteps[i+1]-speedSteps[i])\
- /(tempSteps[i+1]-tempSteps[i])\
- *(cpuTemp-tempSteps[i])\
- +speedSteps[i],1)
- if((fanSpeed != fanSpeedOld) ):
- if((fanSpeed != fanSpeedOld)\
- and ((fanSpeed >= FAN_LSPD) or (fanSpeed == 0))):
- fan.ChangeDutyCycle(fanSpeed)
- fanSpeedOld = fanSpeed
- print("Speed is {0}%".format(fanSpeed))
- time.sleep(WAIT_TIME) # Wait until next refresh
- except(KeyboardInterrupt): # If a keyboard interrupt occurs (ctrl + c), the GPIO is set to 0 and the program exits.
- print("Cancelled... Fan OFF")
- GPIO.cleanup()
- sys.exit()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement