Skip to content

Instantly share code, notes, and snippets.

@romamaslennikov
Forked from stepanmas/Raspberry pi fan control
Last active February 12, 2022 12:23
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save romamaslennikov/6dcacb41bb7cd711baf190e5c92aaa64 to your computer and use it in GitHub Desktop.
Save romamaslennikov/6dcacb41bb7cd711baf190e5c92aaa64 to your computer and use it in GitHub Desktop.
#!/usr/bin/env python3
# Author: Edoardo Paolo Scalafiotti <edoardo849@gmail.com>
import os
from time import sleep
import signal
import sys
import RPi.GPIO as GPIO
pin = 12 # The pin ID, edit here to change it
maxTMP = 55 # The maximum temperature in Celsius after which we trigger the fan
fan_off_on = 45
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return ()
def getCPUtemperature():
#res = os.popen('/opt/vc/bin/vcgencmd measure_temp').readline()
res = os.popen('cat /sys/class/thermal/thermal_zone0/temp').readline()
#temp = (res.replace("temp=", "").replace("'C\n", ""))
temp = (int(res.replace("\n", "")) / 1000)
#print(f"Temperature: {temp}")
return temp
def fanON():
#print('ON')
setPin(True)
return ()
def fanOFF():
#print('OFF')
setPin(False)
return ()
def getTEMP():
CPU_temp = float(getCPUtemperature())
if CPU_temp > maxTMP:
fanON()
elif CPU_temp < fan_off_on:
fanOFF()
return ()
def setPin(mode): # A little redundant function but useful if you want to add logging
GPIO.output(pin, mode)
return ()
try:
setup()
while True:
getTEMP()
sleep(5) # Read the temperature every 5 sec, increase or decrease this limit if you want
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
GPIO.cleanup() # resets all GPIO ports used by this program
# And after, you need add to the crontab a next string
# @reboot python /usr/local/bin/fan_control
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment