Hackernoon logoRaspberry Pi temperature controlled fan by@romanzipp

Raspberry Pi temperature controlled fan

Roman Zipp Hacker Noon profile picture

@romanzippRoman Zipp

Web Developer

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.


  • 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:


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.


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.


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)

timestamp() {
date +”%Y-%m-%d %T”
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 ]
echo `timestamp` ” Warning: Fan started.”>>$LOGDIR
echo ”1”>/sys/class/gpio/gpio2/value
elif [ $TEMP -le $VALUE ] && [ $STATUS -eq 1 ]
echo `timestamp` ” Warning: Fan stopped.”>>$LOGDIR
echo ”0”>/sys/class/gpio/gpio2/value

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.


Join Hacker Noon

Create your free account to unlock your custom reading experience.