DC motors: speed with PWM, direction with an H-bridge

A brushed DC motor is the simplest motor. When you apply a voltage, it turns. When you reverse the voltage, it turns in the opposite direction. The speed increases with the voltage, and the torque increases with the current. An ESP32 pin supplies only milliamps, so the motor operates on its own supply. A MOSFET (one direction) or an H-bridge driver (two directions) switches the supply. PWM on that switch sets the average voltage, and with it the speed.

Five small brushed DC motors of different sizes
Small brushed DC motors in different sizes. Each has two terminals: reverse the voltage to reverse the direction.
Photo: Adafruit (lady ada), CC BY-SA 3.0

H-bridge simulator

Click a switch (Q1–Q4) to open or close it, or use the buttons
+V motor supply GND A B Q1 Q2 Q3 Q4 ⚠ SHOOT-THROUGH: short circuit
Mode
Coast
Average motor voltage
0.0 V
Motor speed
0%
TB6612 pins
IN1 L · IN2 L

How brushed DC motors operate

Voltage → speed, current → torque

When the motor turns, it operates as a generator. It makes a back-EMF that opposes the supply. With no load, the motor turns faster until the back-EMF is almost equal to the supply, so the speed is approximately proportional to the voltage. When you apply a load, the motor turns more slowly and the back-EMF decreases. More current then flows and makes more torque.

Stall current and start current

When the motor does not turn, there is no back-EMF. Only the coil resistance limits the current. At each start and each stall, the motor uses the stall current. This current is frequently 5–10× the running current. Choose drivers and supplies for the stall current. To find it, measure the coil resistance with a multimeter on the motor terminals. Stall current ≈ supply voltage ÷ coil resistance.

Electrical noise

The brushes make sparks when they switch the coils. These sparks put noise on the power lines. Solder a 0.1 µF ceramic capacitor across the motor terminals. You can also solder one capacitor from each terminal to the metal case. Twist the motor wires. Keep them away from sensor and signal wires.

One direction: a MOSFET and a diode

+6–12 V motor supply M 1N5819 / UF4007 (stripe to +) 0.1 µF IRLZ44N 100 Ω 10 kΩ ESP32 GPIO 4 GND GND
A low-side MOSFET switch for a motor that turns in only one direction (fans, pumps, propellers on a test rig). During the PWM off-times, the diode carries the motor current. The capacitor absorbs the brush noise.

Parts and notes

  • MOSFET: Use a logic-level MOSFET with a rating much more than the stall current of the motor (IRLZ44N, IRLB8721). Do not use the IRF520 module. Refer to MOSFETs.
  • Flyback diode: You must install this diode. A Schottky diode (1N5819, or SS34 for > 1 A) or a fast-recovery diode (UF4007) is good for PWM. A standard 1N4007 is slow. It is satisfactory for on/off switching, but it becomes warm with fast PWM.
  • Capacitor: a 0.1 µF ceramic capacitor across the motor, plus a 100–470 µF electrolytic capacitor across the supply near the circuit.
  • Gate resistor and pull-down resistor: 100 Ω and 10 kΩ. They keep the motor off while the ESP32 boots.
  • This circuit gives only speed control. To reverse the motor or to brake it, use an H-bridge (below).

one_direction.ino


              const int MOTOR_PIN = 4;
              void setup() {
                ledcAttach(MOTOR_PIN, 20000, 8);   // 20 kHz (silent), 0..255
              }
              void loop() {
                ledcWrite(MOTOR_PIN, 255);  delay(2000);   // full speed
                ledcWrite(MOTOR_PIN, 120);  delay(2000);   // approximately half speed
                ledcWrite(MOTOR_PIN, 0);    delay(2000);   // off (coast)
              }
            

Ready-made driver boards

HW-517 MOSFET module

The one-direction circuit above on a small board, with two AOD4184 MOSFETs. Speed control only. You must add the flyback diode.

L298N dual H-bridge

Speed and direction for two motors, with an on-board 5 V regulator. Common in robot kits, but it loses ~2 V and becomes hot.

Two directions: H-bridge driver boards

An H-bridge has four switches around the motor in the shape of the letter H (refer to the simulator above). When you close the diagonal pair Q1+Q4, current flows in one direction. When you close Q2+Q3, current flows in the opposite direction. A driver chip has the four switches, the flyback diodes and shoot-through protection in one package.

DriverMotor voltageCurrent / channelNotes
DRV88332.7–10.8 V~1.2 A (2 A peak)Very good for small robots Two motors. It has MOSFET outputs, so it loses very little voltage. Two PWM pins for each motor.
TB6612FNG4.5–13.5 V1.2 A (3.2 A peak)Popular Two motors. IN1/IN2 for direction, a separate PWM pin, an STBY pin. Logic at 3.3 V.
L298N (red module)5–35 V~2 AOld design Its bipolar transistors lose ~2 V or more. This voltage changes into heat, so the module has a large heatsink. A 6 V motor gets only ~4 V.
BTS7960 (IBT-2)6–27 V10–40 ALarge motors One motor. Scooter and wiper motors. Needs a high-current supply and thick wires.
Brushless motorsA brushless motor needs a different driver. Use an ESC. Refer to Brushless & ESCs. For steppers, refer to Stepper motors.
ESP32 GPIO 25 GPIO 26 GPIO 27 GPIO 33 3V3 GND TB6612FNG PWMA AIN1 AIN2 STBY VCC GND VM AO1 AO2 GND M Motor battery 6–12 V + − all grounds connected
The TB6612FNG module wiring for one motor (motor B uses PWMB, BIN1, BIN2, BO1, BO2). The pin labels are different on some breakout boards. Examine the labels on your board.

Wiring table

TB6612 pinConnect toPurpose
VMMotor battery +Motor power (4.5–13.5 V)
VCCESP32 3V3Logic power
GNDBattery − and ESP32 GNDCommon ground
PWMAGPIO 25Speed (PWM)
AIN1 / AIN2GPIO 26 / 27Direction
STBYGPIO 33 (or 3V3)HIGH = enabled
AO1 / AO2Motor terminalsInterchange them to reverse the “forward” direction

Truth table

IN1IN2PWMResult
HLdutyForward at that speed
LHdutyReverse at that speed
HHanyShort brake (both low switches on)
LLHStop: the outputs are off and the motor coasts

How to choose a driver and a supply

DriverSuitableReason

PWM frequency & power

How to choose the PWM frequency

At less than ~20 kHz, you can hear the coils whine (try the sound button in the simulator). At 20 kHz, the motor is silent. But each switching edge uses a small quantity of energy in the driver. The DRV8833 and TB6612 operate easily at 20 kHz. The L298N operates best at lower frequencies (≈ 1–5 kHz). Very low frequencies (≈ 100 Hz) can give a small increase in torque at low speeds.

Separate motor power

Supply the motors from their own supply rail. Use a separate battery, or the battery voltage with the ESP32 after its own regulator. Do not supply a motor from the 3V3 or 5V pin of the ESP32. Connect the grounds together. When motors start or reverse, the voltage decreases quickly. If the ESP32 is on that same rail, it will brown out and reset. Refer to Power supplies.

Prevent damage to the gears

Do not change immediately from full forward to full reverse. This causes a current spike of up to approximately 2× the stall current (the back-EMF adds to the supply). It also causes stress in the gearbox. Decrease the speed gradually, brake for a short time, then increase the speed gradually in the opposite direction. Most small motors need ~20–40% duty before they overcome friction and start to move.

Code

TB6612FNG

tb6612_motor.ino


              const int PWMA = 25, AIN1 = 26, AIN2 = 27, STBY = 33;
              const int FREQ = 20000;   // 20 kHz: you cannot hear a whine
              const int BITS = 8;       // speed 0..255

              void setup() {
                pinMode(AIN1, OUTPUT);
                pinMode(AIN2, OUTPUT);
                pinMode(STBY, OUTPUT);
                digitalWrite(STBY, HIGH);          // enable the driver
                ledcAttach(PWMA, FREQ, BITS);
              }

              // speed: -255 (full reverse) .. 0 (coast) .. 255 (full forward)
              void drive(int speed) {
                speed = constrain(speed, -255, 255);
                digitalWrite(AIN1, speed > 0 ? HIGH : LOW);
                digitalWrite(AIN2, speed < 0 ? HIGH : LOW);
                ledcWrite(PWMA, abs(speed));
              }

              void brake() {
                digitalWrite(AIN1, HIGH);
                digitalWrite(AIN2, HIGH);
                ledcWrite(PWMA, 255);
              }

              void loop() {
                for (int s = 0; s <= 200; s += 5) { drive(s); delay(30); }   // increase speed gradually
                delay(1000);
                brake(); delay(300);
                for (int s = 0; s >= -200; s -= 5) { drive(s); delay(30); }  // increase reverse speed gradually
                delay(1000);
                drive(0); delay(1000);                                       // coast
              }
            

DRV8833 (two PWM pins per motor)

drv8833_motor.ino


              const int IN1 = 25, IN2 = 26;   // AIN1, AIN2 on the DRV8833 board
              const int FREQ = 20000, BITS = 8;

              void setup() {
                ledcAttach(IN1, FREQ, BITS);
                ledcAttach(IN2, FREQ, BITS);
              }

              // -255..255. Send PWM to one input. Keep the other input LOW.
              void drive(int speed) {
                speed = constrain(speed, -255, 255);
                if (speed > 0)      { ledcWrite(IN1, speed);  ledcWrite(IN2, 0); }
                else if (speed < 0) { ledcWrite(IN1, 0);      ledcWrite(IN2, -speed); }
                else                { ledcWrite(IN1, 0);      ledcWrite(IN2, 0); }   // coast
              }

              void brake() { ledcWrite(IN1, 255); ledcWrite(IN2, 255); }  // both HIGH

              void loop() {
                drive(180);  delay(2000);
                brake();     delay(300);
                drive(-180); delay(2000);
                drive(0);    delay(1000);
              }
            

Many DRV8833 breakouts have an EEP/nSLEEP pin that must be HIGH (frequently, the board already pulls it up). Make sure that the VM voltage is in the range. The maximum is 10.8 V, so a 3S LiPo is too much.

L298N and HW-517

Code for these boards is on their own pages: L298N dual H-bridge (two motors, speed and direction) and HW-517 MOSFET module (one direction, speed only).

Troubleshooting

The ESP32 resets when the motor starts

The start current causes a brownout. Use a separate motor supply and connect only the grounds. Install bulk capacitors (470 µF+) at the driver and 0.1 µF across the motor. Increase the speed gradually. Do not go to full speed immediately.

The motor hums but does not turn

Possible causes: the duty is too low to overcome friction, the supply voltage decreases under load, or the ~2 V drop of an L298N leaves too little voltage for a low-voltage motor. Try a higher duty or a short pulse at 100%.

The driver is hot / shuts down

Possible causes: the current is more than its rating (frequently because of stalls), or the internal losses of an L298N. Compare the stall current with the table above and choose a larger driver. Modern MOSFET drivers stay much cooler.

The motor turns in only one direction

One direction pin does not change. Examine the wiring and print the pin states. With a TB6612, also make sure that STBY is HIGH.

The sensors give incorrect values when the motors operate

The cause is electrical noise. Add capacitors on the motors. Twist the motor wires and keep them away from I²C/sensor wires. Supply the sensors with clean 3.3 V from the ESP32.

Safety

Stalled motors become hot quickly. Keep fingers and hair away from gears and wheels. Lift the wheels of a robot off the bench during tests. Install a fuse in projects that use a battery.

Resources