Skip to content

Instantly share code, notes, and snippets.

@ataffanel
Created April 29, 2019 20:10
Show Gist options
  • Save ataffanel/d286256d5badb259571046c134559cf2 to your computer and use it in GitHub Desktop.
Save ataffanel/d286256d5badb259571046c134559cf2 to your computer and use it in GitHub Desktop.
raspberry pi fan control

place fan_control.service in /etc/systemd/system and then:

$ sudo systemctl enable fan_control
$ sudo systemctl start fan_control
import wiringpi
import time
from subprocess import PIPE, Popen
def init_fan():
wiringpi.pwmSetMode(0) # PWM_MODE_MS = 0
wiringpi.wiringPiSetupGpio()
wiringpi.pinMode(18, 2) # pwm only works on GPIO port 18
wiringpi.pwmSetClock(6) # this parameters correspond to 25kHz
wiringpi.pwmSetRange(128)
def fan_set(percent):
wiringpi.pwmWrite(18, int((percent/100.0)*128))
def get_cpu_temperature():
"""get cpu temperature using vcgencmd"""
process = Popen(['vcgencmd', 'measure_temp'], stdout=PIPE)
output, _error = process.communicate()
return float(output[output.index(b'=') + 1:output.rindex(b"'")])
desired_temperature = 52.0
fan_speed = 100
sum = 0
p_temp = 15
i_temp = 0.4
def get_fan_speed(actual_temperature):
global fan_speed,sum
diff = actual_temperature - desired_temperature
sum = sum + diff
pDiff = diff * p_temp
iDiff = sum * i_temp
fan_speed = pDiff + iDiff
if fan_speed > 100:
fan_speed = 100
if fan_speed < 10:
fan_speed = 0
if sum > 100:
sum = 100
if sum < -100:
sum = -100
return fan_speed
init_fan()
control = 0
while True:
temp = get_cpu_temperature()
control = get_fan_speed(temp)
fan_set(control)
# print(control, temp)
time.sleep(1)
[Unit]
Description=PWM fan control
After=network.target
[Service]
ExecStart=/usr/bin/python3 fan_control.py
WorkingDirectory=/home/pi/bin
StandardOutput=inherit
StandardError=inherit
Restart=always
User=root
[Install]
WantedBy=multi-user.target
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment