ESP32 - Control Fan
This tutorial instructs you how to use ESP32 to control a fan.
Hardware Used In This Tutorial
Or you can buy the following sensor kits:
1 | × | DIYables Sensor Kit (30 sensors/displays) | |
1 | × | DIYables Sensor Kit (18 sensors/displays) |
Introduction to 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 ESP32 to turn on/off a fan. Controlling the speed of a fan will be presented in another tutorial.
Because the fan uses the high voltage, we cannot connect it directly to ESP32, we need to connect fan to ESP32 indirectly via a relay. We have specific tutorials about relay (pinout, how it works, how to program ...), learn about relay in the ESP32 - Relay tutorial
Wiring Diagram
- How to connect ESP32 and controls fan using breadboard (powered via USB cable)
This image is created using Fritzing. Click to enlarge image
- How to connect ESP32 and controls fan using breadboard (powered via Vin pin)
This image is created using Fritzing. Click to enlarge image
- How to connect ESP32 and controls fan using screw terminal block breakout board (powered via USB cable)
- How to connect ESP32 and controls fan using screw terminal block breakout board (powered via Vin pin)
If you're unfamiliar with how to supply power to the ESP32 and other components, you can find guidance in the following tutorial: How to Power ESP32.
ESP32 Code
The below code periodically turns the fan ON/OFF in every 10 seconds.
Quick Instructions
- If this is the first time you use ESP32, see how to setup environment for ESP32 on Arduino IDE.
- Do the wiring as above image.
- Connect the ESP32 board to your PC via a micro USB cable
- Open Arduino IDE on your PC.
- Select the right ESP32 board (e.g. ESP32 Dev Module) and COM port.
- Copy the above code and paste it to Arduino IDE.
- Compile and upload code to ESP32 board by clicking Upload button on Arduino IDE
- See the fan's state
Line-by-line Code Explanation
The above ESP32 code contains line-by-line explanation. Please read the comments in the code!
Video Tutorial
Making video is a time-consuming work. If the video tutorial is necessary for your learning, please let us know by subscribing to our YouTube channel , If the demand for video is high, we will make the video tutorial.