Last active 1 year ago

fancontrol.py Raw
1#! /usr/bin/python
2# PWM fan speed controller
3
4import RPi.GPIO as GPIO
5import time
6import signal
7import sys
8import os
9
10# Configuration
11FAN_PIN = 14 # BCM pin used to drive PWM fan
12WAIT_TIME = 10 # [s] Time to wait between each refresh
13PWM_FREQ = 25 # [kHz] 25kHz for Noctua PWM control
14
15# Configurable temperature and fan speed
16MIN_TEMP = 35
17MAX_TEMP = 65
18FAN_LOW = 40
19FAN_HIGH = 100
20FAN_OFF = 0
21FAN_MAX = 100
22
23# Get CPU's temperature
24def getCpuTemperature():
25 res = os.popen('vcgencmd measure_temp').readline()
26 temp =(res.replace("temp=","").replace("'C\n",""))
27 #print("temp is {0}".format(temp)) # Uncomment for testing
28 print("temp:", temp)
29 return temp
30
31# Set fan speed
32def setFanSpeed(speed):
33 print("speed:", speed)
34 fan.start(speed)
35 return()
36
37# Handle fan speed
38def handleFanSpeed():
39 temp = float(getCpuTemperature())
40 # Turn off the fan if temperature is below MIN_TEMP
41 if temp < MIN_TEMP:
42 setFanSpeed(FAN_OFF)
43 #print("Fan OFF") # Uncomment for testing
44 # Set fan speed to MAXIMUM if the temperature is above MAX_TEMP
45 elif temp > MAX_TEMP:
46 setFanSpeed(FAN_MAX)
47 #print("Fan MAX") # Uncomment for testing
48 # Caculate dynamic fan speed
49 else:
50 step = (FAN_HIGH - FAN_LOW)/(MAX_TEMP - MIN_TEMP)
51 temp -= MIN_TEMP
52 setFanSpeed(FAN_LOW + ( round(temp) * step ))
53 #print(FAN_LOW + ( round(temp) * step )) # Uncomment for testing
54 return ()
55
56try:
57 # Setup GPIO pin
58 GPIO.setwarnings(False)
59 GPIO.setmode(GPIO.BCM)
60 GPIO.setup(FAN_PIN, GPIO.OUT, initial=GPIO.LOW)
61 fan = GPIO.PWM(FAN_PIN,PWM_FREQ)
62 setFanSpeed(FAN_OFF)
63 # Handle fan speed every WAIT_TIME sec
64 while True:
65 handleFanSpeed()
66 time.sleep(WAIT_TIME)
67
68except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
69 setFanSpeed(FAN_HIGH)
70 #GPIO.cleanup() # resets all GPIO ports used by this function
fancontrol.sh Raw
1#! /bin/sh
2# fancontrol starter script
3
4# Carry out specific functions when asked to by the system
5case "$1" in
6 start)
7 echo "Starting fancontrol.py"
8 /usr/local/bin/fancontrol.py &
9 ;;
10 stop)
11 echo "Stopping fancontrol.py"
12 pkill -f /usr/local/bin/fancontrol.py
13 ;;
14 *)
15 echo "Usage: /etc/init.d/fancontrol.sh {start|stop}"
16 exit 1
17 ;;
18esac
19
20exit 0