In this short post I want to show how to add a cooling fan to your Raspberry Pi controlled IoT system.
Certainly first step to keeping your processor cool is to allow for sufficient heat exchange using a heat-sink – also called passive cooling.

Additional active cooling should preferably only run when needed. So obviously the activation/deactivation of the cooling fan should depend on the temperature of the Raspberry Pi CPU.

The Required Hardware

This low cost fan does the job. It is rated for 12V, however the 5V supplied from the Raspberry Pi are sufficient to run it at high enough RPM (revolutions per minute).
Below image uses a relay to switch the fan on and off. This is due to having it added to a project such as the garden sprinkler.
The fan is switched on and off simply by connecting/disconnecting VDD over the relay. So only VDD and GND are connected. I have the yellow control cable not connected, as I was not planning to control the fan speed.

The Control Software

Below Python code determines the temperature of the processor (in getCPUtemperature()). If the temperature is higher then the value specified in MAX_TEMP, the fan is started by calling the function startFan().
If the measured temperature is below or equal MAX_TEMP, the fan is disabled. That’s it…


import RPi.GPIO as GPIO
import time
import os

MAX_TEMP = 50.0         # Max allowable temperature...
FAN_PORT = 20           # The Raspberry Pi port that activates the fan...

# Return CPU temperature as a character string                                 $
def getCPUtemperature():
    res = os.popen('vcgencmd measure_temp').readline()

def startFan(fan):
        print("Starting fan ..."),
        GPIO.setup(fan, GPIO.OUT)
        GPIO.output(fan, GPIO.LOW)    # Open valve

def stopFan(fan):
        print("Stopping fan ... "),
        GPIO.setup(fan, GPIO.OUT)
        GPIO.output(fan, GPIO.HIGH)   # Close valve

def run():
        cpuTemp = getCPUtemperature()
        if float(cpuTemp) > MAX_TEMP:
                print("CPU is too hot" + cpuTemp + " ... Starting the fan...")
                print("Not too hot ...  Sopping the fan ...")


if __name__=="__main__":
                print("Had issues ...")

Making it Work

Above code needs to be called regularly to check for the processor temperature, to activate the fan if the temperature is too high, or to deactivate the fan if temperature is ok.
This is done by adding following line to > sudo crontab -e.

*/8 * * * * nohup /home/pi/flaskSprinkler/ &

This line runs every 8 minutes the script listed above. That’s it.

If you have any comments or questions please leave me a note below.