Motor Speed Control: PWM + IRLZ44N MOSFET and a Flyback Diode
A GPIO cannot drive even a small motor, but a logic-level MOSFET switches amps from 3.3 V. We control the speed with a potentiometer and cover logic-level transistors, the gate resistor and the flyback diode.
About the project
An ESP32 pin gives up to 20–40 mA, while even a toy motor draws hundreds of milliamps at start-up. You need a switch, and the simplest one is an N-channel MOSFET between the motor and ground. The ESP32 puts PWM on the gate, and the transistor switches the motor with the same duty cycle.
What you need
- ESP32 DevKit
- IRLZ44N MOSFET (or an AO3400 on a breakout)
- 3–6 V DC motor
- 1N4007 diode (or the faster 1N5819)
- 10 kΩ resistor
- 10 kΩ potentiometer
- A separate 5 V supply for the motor
Wiring
+5V (PSU) ──┬──────────── (+) motor (−) ──┬── D (drain)
└──|◀── 1N4007 ───────────────┘ IRLZ44N
(diode stripe to +) GPIO25 ── G (gate)
10 kΩ: G → S
GND (PSU) ── ESP32 GND ────────────────────── S (source)
- Potentiometer: outer pins to 3V3 and GND, wiper to GPIO34.
- The supply ground and the ESP32 ground are shared.
Three rules for a MOSFET switch
- Logic level. The IRLZ44N gate is fully on from ~3 V. The popular IRF540N only half-opens at 3.3 V: it heats up and the motor barely turns. The simulator warns about this.
- A 10 kΩ resistor from gate to source. While the ESP32 boots, the GPIO floats, and noise can switch the transistor on. The resistor holds it off.
- A flyback diode across the motor. The winding is an inductor: when the transistor cuts the current abruptly, it produces a spike of tens of volts that punches through the transistor. A diode placed in reverse gives that current a path to circulate.
Code
// Motor speed control: potentiometer → PWM → logic-level MOSFET (IRLZ44N)
const int POT = 34;
const int GATE = 25;
void setup() {
Serial.begin(115200);
ledcAttach(GATE, 20000, 8); // 20 kHz: above hearing, no motor whine
}
void loop() {
int duty = map(analogRead(POT), 0, 4095, 0, 255);
ledcWrite(GATE, duty);
Serial.printf("duty %3d%%\n", duty * 100 / 255);
delay(300);
}
Good to know
- PWM frequency. At 1–5 kHz the motor whines unpleasantly; at 20 kHz it is silent. A very high frequency (above 50 kHz) without a gate driver heats the transistor.
- Low speed. Below ~20 % duty the motor may not start at all: there is not enough torque to overcome friction. Start from a higher value.
- Direction. One MOSFET turns the motor one way only. Reversing needs an H-bridge such as the L298N (it has its own article).
In the simulator
The ammeter in series shows the motor current. Try removing the diode, using an IRF540N instead of the IRLZ44N, or wiring the motor straight to a GPIO: the simulator explains why each of these is a bad idea.