Raspberry Pi - Fan
This tutorial instructs you how to use Raspberry Pi to control a fan. A different tutorial will be devoted to controlling the speed of the fan.
Hardware Preparation
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Additionally, some of these links are for products from our own brand, DIYables.
Overview of DC Fan
Pinout
A DC fan usually has two pins:
- Negative (-) pin (black): needs to be connected to the negative wire of DC power supply
- Positive (+) pin (red): needs to be connected to the positive wire of DC power supply
The voltage of the DC power supply should be equal to the voltage specified by the fan. In this tutorial, we will use 12VDC and 5VDC fans.
How to Control Fan
- If DC fan is powered by 12V/5V power supply, it run with full speed.
- If DC fan is powered by 12V/5V PWM signal, The fan's speed can be controlled.
This tutorial instructs you how to use Raspberry Pi to turn a 12V/5V fan on or off. We will cover controlling the fan's speed in another tutorial.
To control the fan on off, we need to use a relay between the Raspberry Pi and the fan. This relay can be used by Raspberry Pi to switch the fan on or off.
If you are unfamiliar with relays (pinout, operation, programming, etc.), please refer to the Raspberry Pi - Relay tutorial for more information.
Wiring Diagram
This image is created using Fritzing. Click to enlarge image
To simplify and organize your wiring setup, we recommend using a Screw Terminal Block Shield for Raspberry Pi. This shield ensures more secure and manageable connections, as shown below:
Please note that if you use 5V fan, you need to use 5V power adapter.
Raspberry Pi Code
Detailed Instructions
- Make sure you have Raspbian or any other Raspberry Pi compatible operating system installed on your Pi.
- Make sure your Raspberry Pi is connected to the same local network as your PC.
- Make sure your Raspberry Pi is connected to the internet if you need to install some libraries.
- If this is the first time you use Raspberry Pi, See how to set up the Raspberry Pi
- Connect your PC to the Raspberry Pi via SSH using the built-in SSH client on Linux and macOS or PuTTY on Windows. See to how connect your PC to Raspberry Pi via SSH.
- Make sure you have the RPi.GPIO library installed. If not, install it using the following command:
- Create a Python script file fan.py and add the following code:
- Save the file and run the Python script by executing the following command in the terminal:
- Check out the fan's state.
The script runs in an infinite loop continuously until you press Ctrl + C in the terminal.
Code Explanation
Check out the line-by-line explanation contained in the comments of the source code!