Temperature controlled fan

I’ve been trying these last couple days to write a simple program to turn a fan on when my pi hits a specific temperature and then power down once it has cooled. I have looked all over through forums to find an example of other people doing similar things. I did manage to find one such instance but I have been completely unable to get his code to work properly. I think the problem is a combination of rasbian-osmc differences, and him using an older version of python. I’m still quite new to the world of linux and code in general, I have a little experience in VBA doing very simple programs but that is all. Below is the code I have been attempting to use. Any assistance in this matter would be greatly appreciated.

#!/usr/bin/env python3 import time import os import RPi.GPIO as GPIO GPIO.setmode(GPIO.BOARD) GPIO.setup(12, GPIO.OUT) GPIO.setwarnings(False) def getCPUtemperature(): res = os.popen('vcgencmd measure_temp').readline() return(res.replace("temp=","").replace("'C\n","")) def fanON(): GPIO.output(12, False) return() def fanOFF(): GPIO.output(12, True) return() def getTEMP(): CPU_temp = float(getCPUtemperature()) if CPU_temp>40: fanON() else: fanOFF() return() while 1: getTEMP() time.sleep(45)

Temp >40 should not be concerning. The Pi is designed to run at temps up to 85, at which point it already has logic in place to shutdown to protect itself.

Normal Pi CPU temperature is on the order of 40 - 60 degrees and will self throttle at 85 degrees by disabling the dynamic turbo if you exceed 85 degrees.

So unless you live in a particularly hot climate or the Pi has no ventilation you wouldn’t normally need to worry about temperature. Certainly a temperature controlled fan is overkill.

Then fan is not just for the pi but I will be running a hdd right next to it in an enclosed box with no air-flow (other than the fan I hope to be able to get working). I realize a fan (a small 40x10) is probably overkill but still I think it would be really cool.

I have a 5v mini fan I would like to put in my rpi3 case as its not well ventilated.

I’ve read that the 5v is little noisy some say to power it using the 3.3v pins instead as it will spin slower. Will this damage pi?

I would also like it to turn on after certain temp if anyone has working script. Not sure if one above still works.

Thanks for any info.

You probably need to consider the following:

  1. Using PWM facility of a GPIO pin. Allows setting of the Duty Cycle. So speed of fan can be varied.

  2. Fan speed can be increased as temp increases, and reduced as temp decreases.

  3. Fan could be switched off below a pre-determined temp, say 65C.

  4. Do an automatic shutdown if the temp goes beyond an acceptable upper temp, say 85C.

  5. On initial startup of fan, run at 100% and then drop down to a lower running speed, say 80%. Helps to get fan going initially and remove any heat buildup (in a case).

  6. Switch fan off if some kind of interrupt occurs, such as a shutdown operation.

  7. Spend some time asleep in the controlling routine, wake on regular basis to check temp and alter fan as needed.

Hi,
I did something similar (Pi 3, 5v fan connected to 5v, switched on/off as needed using python script).

My script works 100% when run as: sudo python run-fan.py (Seems to need “sudo” else I get the following error: RuntimeError: No access to /dev/mem. Try running as root!)

BUT - I need the script to autorun when I reboot the PI. I tried editing the rc.local file but it does not seem to work.

Someone else sugested using CRON but begin quite new to Linux, I am a bit lost here!

any pointers on how to get the script running? Also, please see the script below (if anyone is interested in doing something similar).

Basically seems to be the same (similar) script as above?

run-fan.py

#!/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 = 18 # 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

Just an update for - to get your script to run automatically, edit /etc/rc.local using the following command on the command line (via ssh):
sudo nano /etc/rc.local
and add the following line before the line that says “exit 0” (replace the path and python script file name with your own values as needed)
su - osmc -c "sudo python /home/osmc/development/run-fan.py &" &

WARNING: Please make sure the file ends with “exit 0” as removing this can cause your system to not boot anymore!!!