DC motor guides · On this page

Control a DC Motor with an L298N and an ESP32

Turn a knob and a DC motor speeds up, slows down and reverses, driven by an ESP32 through an L298N. The L298N reads anything from 2.3 V as HIGH, so the ESP32's 3.3 V pins drive it directly; the knob is read in millivolts, which the ESP32 corrects with its own calibration.

This guide uses an ESP32 DevKitC, the common ESP32-WROOM-32 board. For the L298N itself, its jumpers and how the H-bridge works, see the DC motor guide.

Try it first, no parts needed

This is the whole project on an ESP32, running in your browser. Press Run simulation, then turn the knob: right of the middle the motor runs forward, left of it backward, faster the further you turn.

Ready
Open in Cirkit Designer

The knob on GPIO 34

Centre stops the motor; right runs it forward, left backward. The sketch reads it every 200 ms.

50 %

ESP32 serial monitor115200 baud

Output appears here when the simulation runs.

What the code does

The sketch is the Arduino one with ESP32 pins, and it reads the knob in millivolts: it sets the motor's direction with IN1 and IN2 and its speed with ENA, and prints both on the Serial Monitor.

Esp32KnobMotor.ino
// Drive a DC motor through an L298N from an ESP32 with a knob. Right of centre it runs
// forward, left of centre backward, faster the further you turn; near the centre it stops.
const int ENA = 23;  // speed: PWM
const int IN1 = 22;  // direction
const int IN2 = 21;
const int KNOB = 34;

const int CENTRE = 1650;    // mV: the knob's middle, half of 3.3 V
const int SPAN = 1450;      // mV either side: the ESP32 reads up to about 3.1 V
const int DEAD_BAND = 130;  // mV this close to the centre, the motor stops
const int MAX_SPEED = 210;  // about 5.3 V average on 9 V: within a TT motor's 3-6 V

void setup() {
  Serial.begin(115200);
  pinMode(ENA, OUTPUT);
  pinMode(IN1, OUTPUT);
  pinMode(IN2, OUTPUT);
}

void loop() {
  // In millivolts, which the ESP32 calibrates; its raw readings aren't linear.
  int offset = analogReadMilliVolts(KNOB) - CENTRE;
  int speed = 0;
  if (offset > DEAD_BAND) {
    digitalWrite(IN1, HIGH);  // forward
    digitalWrite(IN2, LOW);
    speed = constrain(map(offset, DEAD_BAND, SPAN, 0, MAX_SPEED), 0, MAX_SPEED);
    Serial.print("Forward, speed ");
  } else if (offset < -DEAD_BAND) {
    digitalWrite(IN1, LOW);   // backward
    digitalWrite(IN2, HIGH);
    speed = constrain(map(-offset, DEAD_BAND, SPAN, 0, MAX_SPEED), 0, MAX_SPEED);
    Serial.print("Backward, speed ");
  } else {
    digitalWrite(IN1, LOW);   // stop
    digitalWrite(IN2, LOW);
    Serial.print("Stopped, speed ");
  }
  analogWrite(ENA, speed);
  Serial.println(speed);
  delay(200);
}
  1. const int ENA = 23;  // speed: PWM

    The GPIOs wired to the L298N. Any ESP32 output can give PWM, so ENA can be on any of them; see which GPIO.

  2. const int KNOB = 34;

    The knob's middle leg, on GPIO 34. GPIO 34 to 39 are inputs only, which suits a knob and leaves the outputs free.

  3. const int SPAN = 1450;      // mV either side: the ESP32 reads up to about 3.1 V

    With the knob on 3V3, its middle is 1650 mV. Espressif gives the ESP32's range as 150 to 3100 mV, so the sketch counts 1450 mV either side as fully turned, a little short of each end.

  4. int offset = analogReadMilliVolts(KNOB) - CENTRE;

    analogReadMilliVolts gives the voltage in millivolts, corrected by the chip's own calibration, unlike the raw analogRead. Taking away the middle makes it negative to the left, positive to the right.

  5. speed = constrain(map(offset, DEAD_BAND, SPAN, 0, MAX_SPEED), 0, MAX_SPEED);

    As on the Uno, map turns how far the knob is turned into a speed from 0 to 210; constrain keeps it there when the knob reads past 1450 mV.

  6. analogWrite(ENA, speed);

    Sets the speed, 0 to 255, as on an Arduino. The ESP32 makes the PWM with its LED controller, and the L298N reads its 3.3 V pulses as HIGH.

Why 3.3 V is enough

ST's datasheet for the L298 reads any input from 2.3 V as HIGH and up to 1.5 V as LOW, whatever its own logic supply. The ESP32's HIGH is 3.3 V and its LOW 0 V, well either side, so its GPIOs drive ENA, IN1 and IN2 directly, with no level shifter. The motor's power comes from the battery through the L298N, not from the ESP32.

The knob is different: it's an input to the ESP32, and an ESP32 pin must never see more than 3.6 V. That's why it goes on 3V3, not on the L298N's 5 V. The figure under this follows the L298N in the running circuit.

The H-bridge, liveExample: forward at 210 of 255Run the circuit at the top, and this follows the L298N as the sketch drives it.
IN1, GPIO 22
HIGH
IN2, GPIO 21
LOW
ENA, GPIO 23
PWM 82%
Battery +GNDMOUT1OUT2
Bridge
Forward
Motor
+5.3 V

The motor: forward, switched on 82% of the time, averaging +5.3 V.

Build it on an ESP32

Now with real parts. Wire it, get the code, then upload it and turn the knob. Not sure which pin is which? See the L298N pinout.

You'll need

  • An ESP32 DevKitC (ESP32-WROOM-32) and a USB cable that carries data
  • An L298N motor driver module, with the jumper taken off ENA
  • A small DC motor rated for 6 V or more, such as a TT gear motor, and a 9 V battery or six AA cells
  • A 10 kΩ potentiometer, the knob
  • Jumper wires, a breadboard, and a small screwdriver for the terminals
  • Software to upload the sketch: either Cirkit Designer, free in your browser, or the Arduino IDE with Espressif's ESP32 boards installed
  1. Wire it

    Take the jumper off ENA first. Then four wires from the L298N to the ESP32, the battery and the motor as on the Arduino, and the knob on 3V3 and GPIO 34. Connect the battery last.

    Tap a connection to see it on the circuit.

    FromConnect toShow
    L298N GNDESP32 GNDShow
    L298N ENAESP32 GPIO 23Show
    L298N IN1ESP32 GPIO 22Show
    L298N IN2ESP32 GPIO 21Show
    Battery +L298N 12VShow
    Battery −L298N GNDShow
    L298N OUT1Motor leadShow
    L298N OUT2Motor's other leadShow
    Knob outer legESP32 3V3Show
    Knob middle legESP32 GPIO 34Show
    Knob other outer legESP32 GNDShow

    The knob goes on 3V3, not 5 V. Its middle leg carries up to the voltage across it to GPIO 34, and an ESP32 pin takes 3.6 V at most. Never connect the L298N's 5V terminal to the ESP32.

  2. Get the code

    I'm using:

    Steps 2 and 3 follow the tool you pick.

    Open in Cirkit Designer

    The project opens with the sketch already in it. It needs no library.

    Install the ESP32 boards first, as Espressif's installing guide shows. In Preferences, add https://espressif.github.io/arduino-esp32/package_esp32_index.json to Additional Board Manager URLs; then open Tools → Board → Boards Manager, search for esp32 and install it. The sketch needs no library. Copy it into a new sketch:

    How it works line by line is in what the code does, above.

  3. Upload and check it

    Plug in your ESP32. In Cirkit, open the Build tab, then Upload firmware: click Select Port and pick your board, then Upload to Device. The first time, Cirkit asks you to install Cirkit Create Agent, a small desktop helper that lets it reach the board over USB. Then open Upload output and serial monitor and click Start Serial Monitor. Connect the battery last, with the knob in the middle.

    Show me where to click in Cirkit
    DC motor and L298N on an ESP32FileEditExportHelp
    DesignCodeSimulateBuild
    1Parts & purchasing2Assemble3Upload firmware
    ESP32Edit Code

    Board

    ESP32 Change

    2

    Port

    Select PortCOM4 Connected

    3

    Upload

    Upload to DeviceUploading...Upload successful

    4

    Check that it works

    Your project should now run as designed.

    Upload output and serial monitor
    Compile / Upload Output
    Sketch uses 299367 bytes (22%) of program storage space. Maximum is 1310720 bytes.
    Global variables use 21072 bytes (6%) of dynamic memory, leaving 306608 bytes for local variables. Maximum is 327680 bytes.
    Device SerialStop

    Read serial data from your device.

    Start Serial Monitor
    Listening on COM4 at 115200 baud
    Stopped, speed 0
    Stopped, speed 0
    Forward, speed 58
    Forward, speed 138
    Forward, speed 210
    Forward, speed 210
    Select port

    Select a device port

    Select the device port for uploading code and serial communications

    COM4 (ESP32)
    1. Open Build
    2. Choose Upload firmware
    3. Click Select Port
    4. Pick COM4 (ESP32)
    5. Click Upload to Device
    6. Open Upload output and serial monitor
    7. Click Start Serial Monitor

    In the Arduino IDE, choose ESP32 Dev Module and its port from the board menu, press Upload, then open the Serial Monitor and set it to 115200 baud. Connect the battery last, with the knob in the middle.

    Show me where to click in the Arduino IDE
    Select BoardESP32 Dev Module

    Select other board and port

    ESP32 Dev ModuleCOM4
    Esp32KnobMotor.ino
    // Drive a DC motor through an L298N from an ESP32 with a knob. Right of centre it runs
    // forward, left of centre backward, faster the further you turn; near the centre it stops.
    const int ENA = 23;  // speed: PWM
    const int IN1 = 22;  // direction
    const int IN2 = 21;
    const int KNOB = 34;
    OutputSerial Monitor115200 baud

    Compiling sketch...

    Sketch uses 299367 bytes (22%) of program storage space. Maximum is 1310720 bytes.

    Global variables use 21072 bytes (6%) of dynamic memory, leaving 306608 bytes for local variables. Maximum is 327680 bytes.

    Uploading...

    Stopped, speed 0

    Stopped, speed 0

    Forward, speed 58

    Forward, speed 138

    Forward, speed 210

    Forward, speed 210

    Done uploading.

    1. Click the board menu
    2. Pick ESP32 Dev Module on COM4
    3. Click Upload
    4. Wait for Done uploading
    5. Click Serial Monitor
    6. Check it is set to 115200 baud

    It works when:

    • The L298N's power LED lights when the battery is connected.
    • After a few start-up lines from the ESP32's boot ROM, the Serial Monitor prints Stopped, speed 0 with the knob in the middle, and the motor stands still.
    • Turning right, the motor runs forward, faster the further you turn, up to Forward, speed 210; turning left, it runs backward.

    Not working? See troubleshooting.

    Next guideNext: build an obstacle-avoiding carTwo motors on the same L298N and an HC-SR04 at the front, on an Arduino Uno: the car drives until something is closer than 25 cm, then backs up and turns.

Which ESP32 pins to use

Any ESP32 GPIO that can be an output can drive ENA, IN1 or IN2; GPIO 23, 22 and 21 are three. The knob needs a pin of ADC1, GPIO 32 to 39, which keeps working when Wi-Fi is on. Avoid the pins in this table: some can't be outputs, and the others are used for flash memory, for choosing how the chip boots, or for the USB serial connection.

AvoidClassic ESP32ESP32-S3
Input only (fine for the knob)GPIO 34 to 39None
FlashGPIO 6 to 11GPIO 26 to 32, and 33 to 37 on modules with octal flash or octal PSRAM
Boot (strapping)GPIO 0, 2, 5, 12 and 15GPIO 0, 3, 45 and 46
Serial (UART0)GPIO 1 (TX) and 3 (RX)GPIO 43 (TX) and 44 (RX)
Native USBNoneGPIO 19 and 20, the USB port's D− and D+

Troubleshooting

Find your symptom; the checks under it run from the most common cause down.

The motor doesn't turn

  • The L298N's GND is wired to the ESP32's GND. It goes to the battery's − as well.
  • ENA, IN1 and IN2 are on GPIO 23, 22 and 21. Those are the pins in the sketch.
  • The jumper is off ENA. With it on, ENA is tied to 5 V: GPIO 23 can't set the speed, and driving it LOW shorts that 5 V.
  • The battery and the motor are connected. Check them as in the DC motor guide.

The motor never stops, or never reaches full speed

  • The knob is on 3V3. On 5V its middle reads high, and it may damage GPIO 34.
  • Your board reads a little differently. Print analogReadMilliVolts(KNOB) at both ends and in the middle, and set CENTRE and SPAN to match.

Nothing in the Serial Monitor, or garbled characters

  • The Serial Monitor is set to 115200 baud. It must match Serial.begin(115200). The ESP32's own start-up lines come first at the same speed.

No port appears for the ESP32

  • The cable carries data. The board's USB port carries its serial link as well as power, so a cable that only charges powers the board but shows no port.
  • The board's USB-to-serial chip has its driver. Its name, such as CP210x, is printed on the chip near the USB socket. The driver usually installs itself; if no port appears, install it from the chip's maker (Silicon Labs for a CP210x).

The upload stops at Connecting..., then says Failed to connect

  • The board is in download mode. Hold BOOT, press and release EN (RST on some boards), then release BOOT, and upload again.

FAQ

Do I need a level shifter between the ESP32 and the L298N?

No. The L298's inputs read HIGH from 2.3 V, so 3.3 V is enough, and nothing comes back from the L298N to the ESP32.

Can I power the ESP32 from the L298N's 5V terminal?

The terminal does give 5 V with the 5V-EN jumper on and 7 V or more on 12V; Handson says to fit that jumper only for supplies under 12 V. A DevKitC's 5V pin takes 5 V. This guide keeps the ESP32 on USB while you work on it; don't connect both at once.

Why not use analogRead?

analogRead gives the raw reading, 0 to 4095, which Espressif doesn't calibrate; analogReadMilliVoltsgives calibrated millivolts, so the knob's middle lands near 1650 mV on any board.

Does the same code work on an ESP32-S3?

Yes, with GPIOs changed to ones the S3 board brings out, and the knob on an ADC1 pin, GPIO 1 to 10. In the Arduino IDE, choose ESP32S3 Dev Module.

Simulating the L298N on an ESP32 in Cirkit Designer

Cirkit runs your compiled sketch on an emulated ESP32, with the L298N and motor modelled as in the DC motor guide: GPIO 23's 3.3 V pulses read as HIGH, and the motor turns at a speed set by their average. The knob gives GPIO 34 its exact share of 3.3 V, so the simulated readings land on the sketch's centre and span; a real board's calibration varies a little.

References