raspberry pi fan control

Almost the most simple code to control raspberry pi fan.

import RPi.GPIO as GPIO
import time
import commands

fan_pin = 12
GPIO.setwarnings(False)
GPIO.setmode(GPIO.BOARD)
GPIO.setup(fan_pin, GPIO.OUT)
def get_gpu_temp():
gpu_temp = commands.getoutput( ‘/opt/vc/bin/vcgencmd measure_temp’ ).replace( ‘temp=’, ” ).replace( ‘\’C’, ” )
return float(gpu_temp)
while 1:
gpu_temp_loop = get_gpu_temp()
print ‘GPU temp:’, gpu_temp_loop
if gpu_temp_loop > 50:
GPIO.output(fan_pin, 1)
elif gpu_temp_loop < 35:
GPIO.output(fan_pin, 0)
time.sleep(5)
That is All.
if you want use the CPU temperature instead, try the code below.
#def get_cpu_temp():
# tempFile = open( “/sys/class/thermal/thermal_zone0/temp” )
# cpu_temp = tempFile.read()
# tempFile.close()
# return float(cpu_temp)/1000