ESP32 - DC Motor
This is a compact build guide. The full tutorial, with the wiring diagram and a line-by-line walkthrough of the code, is here: https://esp32io.com/tutorials/esp32-dc-motor
This build shows how to control a DC motor's speed and direction from an ESP32 using an L298N motor driver module. The ESP32 can't drive the motor directly because of the voltage and current involved, so the L298N sits between them, protecting the ESP32 while amplifying the PWM signal and switching polarity to reverse the motor.
Supplies
Everything below is what the build uses. The links go to the parts we make and test.
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Narrow
- 38-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- 30-pin ESP32 ESP-WROOM-32 Dev Module - Wide
- ESP32 Uno-form board
- ESP32 S3 Uno-form board
- USB Cable Type-A to Type-C (for USB-A PC)
- USB Cable Type-C to Type-C (for USB-C PC)
- L298N Motor Driver Module
- 5V DC Motor
- 5V Power Adapter for 5V DC motor
- Breadboard
- Jumper Wires
- DC Power Jack
- Screw Terminal Expansion Board for ESP32
- Breakout Expansion Board for ESP32
- Power Splitter for ESP32
- DIYables ESP32 Starter Kit (ESP32 included)
- DIYables ESP32 S3 Starter Kit (ESP32 S3 included)
- DIYables Sensor Kit (18 sensors/displays)
Wiring
The DC motor has two wires, negative (black) and positive (red), which connect to the L298N's OUT1 and OUT2 terminals for motor A. The ESP32 connects to the L298N's IN1, IN2 and ENA pins: IN1/IN2 set direction, ENA carries the PWM speed signal. Power the L298N from the 5V power adapter rather than the ESP32. Before wiring anything, remove all three jumpers on the L298N module.
How It Works
The L298N takes three jobs off the ESP32: it isolates the ESP32 from the motor's higher voltage, it switches the polarity across the motor to set its direction based on the IN1/IN2 signals, and it amplifies the ESP32's PWM signal in current and voltage so it can actually turn the motor. Writing a PWM value to ENA with analogWrite() sets speed from 0 (stopped) to 255 (full speed). Setting IN1 and IN2 to opposite states spins the motor clockwise or anti-clockwise; setting them to the same level (both LOW or both HIGH) stops it, as does dropping the speed to 0.
Code
The sketch runs through the motor's full behavior: it ramps the speed up, reverses the motor's direction by flipping IN1 and IN2, ramps the speed back down, then stops the motor. Speed control uses analogWrite() on the ENA pin, direction control uses digitalWrite() on IN1 and IN2.
esp32-dc-motor.ino - the sketch from the tutorial, unchanged.
Full Tutorial
The complete tutorial, wiring diagram and code explanation: https://esp32io.com/tutorials/esp32-dc-motor