Roman Zipp

@romanzipp

Raspberry Pi temperature controlled fan

We want to setp up an automatic, GPIO and temp controlled fan using a Raspberry Pi without additinal software. After the CPU Core temperature exceeds a specific temperature, the fan starts spinning.

Needed:

  • Raspberry Pi (Model B+) (Buy)
  • Fan (4-Pin, 12V) in this case from an old NVIDIA Graphicscard
  • Pinboard
  • GPIO Connector wires (3x) (Buy)
  • Transistor BC337–40 800mA (Buy)
  • Resistor 1 kΩ 0.5W (Buy)

These hyperlinks are just recommended. You can use similar parts.

Helpful Links:

Plan

We connect Pin 4 (5V out) directly to the fan. 
Pin 6 (Ground) will be connected over the Transistor with the 2nd fan wire.

To activate the Transistor, we need a low volatage, which we gain by Pin 3 (GPIO2). The GPIO Pins have a standard voltage of 3.3V. We reduce this by inserting the Resistor.

Result

If we now switch on Pin 3 (GPIO2), the fan should start to spinn.

Enable GPIO2: (root)

echo ”2”>/sys/class/gpio/export
echo ”out”>/sys/class/gpio/gpio2/direction

Switch on GPIO Pin / Fan (root)

echo ”1”>/sys/class/gpio/gpio2/value

Switch off GPIO Pin / Fan (root)

echo “0”>/sys/class/gpio/gpio2/value

Set up autmoatic temp control

In the following, we will set up the fan so that it starts after reaching a special temperature.

We log into the Raspberry Pi as root.

Prinzip:

The Raspberry Pi autmoaticly checks the core temperature throught the built-in control panel. 
If the temperature exceeds a certain value, the fan will start. 
As long as the temp doesn’t fall below our value, the fan will not stop.

apt-get update && apt-get upgrade
apt-get install nano

Now we locate our directory of the script…

mkdir /home/fan
cd /home/fan

…and create our script.

nano fan.sh

Copy the following content into the script: (Use right mouse button to paste)

#!/bin/sh
timestamp() {
date +”%Y-%m-%d %T”
}
LOGDIR=”/var/log/fan.log”
VALUE=42
TEMP=`vcgencmd measure_temp | cut -c6,7`
STATUS=`cat /sys/class/gpio/gpio2/value`
echo `timestamp` ” Info: Temperature: $TEMP”>>$LOGDIR
if [ $TEMP -ge $VALUE ] && [ $STATUS -eq 0 ]
then
echo `timestamp` ” Warning: Fan started.”>>$LOGDIR
echo ”1”>/sys/class/gpio/gpio2/value
elif [ $TEMP -le $VALUE ] && [ $STATUS -eq 1 ]
then
echo `timestamp` ” Warning: Fan stopped.”>>$LOGDIR
echo ”0”>/sys/class/gpio/gpio2/value
fi

To change the value, you have to edit line 6.

To let the script run in background, we need `cronjob`.

crontab -e

and paste the following content:

* * * * * /home/fan/./fan.sh

(repalce with your path)

The script ist now automaticly executed at every minute.

Topics of interest

More Related Stories