Cool Your Raspberry Pi with a Fan Using Python and GPIO

A step-by-step guide on how to connect a fan to your Raspberry Pi, control it using Python, and monitor its temperature for efficient cooling. …


Updated October 18, 2023

Need help with your Raspberry Pi?
Contact Me!

Do you love silly Raspberry Pi Projects?
Check out my this YouTube Channel!


A step-by-step guide on how to connect a fan to your Raspberry Pi, control it using Python, and monitor its temperature for efficient cooling.

Raspberry Pi is an amazing device that can be used for various projects, including creating servers, automating tasks, or running AI models. However, it generates heat during operation which can affect its performance or even damage some components if left unchecked. One effective way to cool down your Raspberry Pi is by connecting a fan and controlling its speed based on the temperature of the device. In this article, we will discuss how to connect a fan to your Raspberry Pi using GPIO (General Purpose Input/Output) pins and control it using Python. We will also create a simple program to monitor the temperature and adjust the fan speed accordingly.

Materials Required:

  • Raspberry Pi (any model)
  • DC Fan or PC Fan with 5V voltage rating
  • Breadboard (optional, but recommended for easier wiring)
  • Jumper wires
  • Soldering iron and solder (optional)

Step 1: Connect the Fan to Raspberry Pi

First, we need to connect the fan to your Raspberry Pi. There are two types of fans commonly used with Raspberry Pi: DC fans and PC fans. Both work well, but they have different connections.

DC Fan

Connect the negative terminal of the fan (usually marked ‘-') to any ground pin on the Raspberry Pi. Connect the positive terminal (usually marked ‘+') to a GPIO pin through a resistor. You can use any GPIO pin, but for this example, we will use GPIO 18.

Here’s how you can connect it using jumper wires:

  1. Strip the ends of a jumper wire and solder one end to the negative terminal of the fan (if available) or any ground pin on the Raspberry Pi.
  2. Strip another end of a jumper wire and connect it to the positive terminal of the fan.
  3. Connect the other end of this jumper wire to GPIO 18 using a resistor (e.g., a 1kΩ resistor). You can solder the resistor directly to the GPIO pin or use a breadboard for easier connections. Make sure to connect the fan’s positive terminal to the 5V pin on the Raspberry Pi.

PC Fan

Connecting a PC fan is slightly more complex as it requires PWM (Pulse Width Modulation) to control its speed. You can use either a 3-pin or 4-pin connector for this purpose. For this example, we will assume you have a 3-pin connector fan with the following pins:

  1. Ground (usually marked ‘-')
  2. Power (usually marked ‘+')
  3. Control (marked with a square wave symbol)

Connect the ground pin to any ground pin on the Raspberry Pi and the power pin to 5V. Connect the control pin to GPIO 18 using a resistor (e.g., a 1kΩ resistor). You can solder the resistor directly to the GPIO pin or use a breadboard for easier connections.

Step 2: Enable GPIO Interface on Raspberry Pi

Before you can control the fan using Python, you need to enable the GPIO interface. Open the terminal and type:

sudo raspi-config

Navigate to Interfacing Options > GPIO and select ‘Yes’ to enable the GPIO interface. Then reboot your Raspberry Pi by typing:

sudo reboot

Step 3: Write a Python Program to Control the Fan

Now that we have connected the fan and enabled the GPIO interface, we can write a simple Python program to control its speed based on the temperature of the Raspberry Pi.

Create a new file called fan_control.py using your favorite text editor:

nano fan_control.py

Add the following code to this file:

import time
import RPi.GPIO as GPIO
import os

# Setup GPIO pin for the fan
FAN_PIN = 18
GPIO.setmode(GPIO.BCM)
GPIO.setup(FAN_PIN, GPIO.OUT)
fan = GPIO.PWM(FAN_PIN, 50) # 50 Hz frequency
fan.start(0) # Set initial speed to 0%

# Function to get the temperature of the Raspberry Pi
def get_cpu_temp():
    temp = os.popen('vcgencmd measure_temp').readline()
    return float(temp.replace("temp=", "").replace("'C\n", ""))

try:
    while True:
        # Get the current temperature
        temp = get_cpu_temp()
        
        # Calculate the fan speed based on the temperature (example: 50% at 40°C and 100% at 60°C)
        duty_cycle = min(max((temp - 40) * 2, 0), 100)
        
        # Set the fan speed
        fan.ChangeDutyCycle(duty_cycle)
        
        print("Current temperature: {:.2f}°C, Fan speed: {}%".format(temp, duty_cycle))
        time.sleep(10) # Check every 10 seconds
except KeyboardInterrupt:
    fan.stop()
    GPIO.cleanup()

This program sets the fan speed based on the temperature of the Raspberry Pi. The get_cpu_temp() function reads the current temperature using the vcgencmd command. Then, it calculates the duty cycle (fan speed) as a percentage of the difference between the current temperature and 40°C. Finally, it sets the fan speed using the ChangeDutyCycle() method of the PWM object. The program runs in an infinite loop, checking the temperature every 10 seconds.

Step 4: Run the Python Program

To run the fan_control.py script, open a terminal and type:

python fan_control.py

Now your Raspberry Pi will automatically control the fan speed based on its temperature. You can adjust the temperature thresholds in the code to suit your needs or add more advanced cooling algorithms if necessary.