#!/usr/bin/env python3
import os
from time import sleep
import signal
import sys
import RPi.GPIO as GPIO
pin = 27 # The pin ID, edit here to change it
maxTMP = 50 # The maximum temperature in Celsius after which we trigger the fan
sleepTime = 30 # The time to sleep between temp checks
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
temp =(res.replace("temp=","").replace("'C\n",""))
print("temp is {0}".format(temp)) #Uncomment here for testing
return temp
def fanON():
print("Fan on ...")
setPin(True)
return()
def fanOFF():
print("Fan off ...")
setPin(False)
return()
def getTEMP():
CPU_temp = float(getCPUtemperature())
if CPU_temp > maxTMP:
fanON()
sleep(sleepTime) # Sleep additional time in order to ensure that we stay below max temp ...
else:
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(sleepTime) # Read the temperature every x amount of seconds ...
except KeyboardInterrupt: # trap a CTRL+C keyboard interrupt
GPIO.cleanup() # resets all GPIO ports used by this script