Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
this is to control a fan on a raspberry pi with python 3.4 on a bc332 transistor
#!/usr/bin/env python3
# first author: Edoardo Paolo Scalafiotti <edoardo849@gmail.com>
# Edits done by: Marco Bosch <marcogithub@hotmail.com>
import os
from time import sleep
import signal
import sys
import RPi.GPIO as GPIO
pin = 18 # The pin ID, edit here to change it
maxTMP = 49.0 # The maximum temperature in Celsius after which we trigger the fan
minTMP = 40.0 # Edit this sets the cutoff temperture.
global Fan #Edit this makes the variable Fan a global variable
Fan = 0 # Edit this variable is to help the script run for a time to get the temp down to what ever lower limit you set at minTMP
def setup():
GPIO.setmode(GPIO.BCM)
GPIO.setup(pin, GPIO.OUT)
GPIO.setwarnings(False)
return()
def getCPUtemperature():
res = os.popen('vcgencmd measure_temp').readline()
cput =(res.replace('temp=','').replace("\'C\n",""))
#print ("temp is {0}".format(cput)) #Uncomment here for testing
return cput
def fanON():
setPin(True)
return()
def fanOFF():
setPin(False)
return()
def getTEMP(): #code by marco
global Fan
CPU_temp = float(getCPUtemperature())
if Fan == 0:
if CPU_temp > maxTMP:
Fan = 1
fanON()
else:
Fan = 0
fanOFF()
elif Fan == 1:
if CPU_temp > minTMP:
Fan = 1
fanON()
else:
Fan = 0
fanOFF()
else:
Fan = 0
fanOFF() #end
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.