Introduction: How to Drive a DC Motor Using L298N and ESP32 With Arduino IDE

About: Welcome to School Sur Seine !! Here, I offer step-by-step tutorials using the Arduino UNO, ESP32 and Raspberry pi pico wh. I also create small projects that combine multiple modules, sensors, motors, and vario…

In this project, we will learn how to make a DC motor turn using an ESP32 microcontroller and an L298N motor driver module. The L298N is a very popular dual H-bridge driver that allows us to control the direction and speed of a DC motor safely, without connecting the motor directly to the ESP32. This project is suitable for beginners and intermediate makers who want to learn motor control with the ESP32, and it can be easily extended to robotics or automation projects.

-------------------------------------------------------------------------------------------

Dans ce projet, nous allons apprendre à faire tourner un moteur à courant continu en utilisant un microcontrôleur ESP32 et un module pilote de moteur L298N. Le L298N est un driver H-bridge double très populaire qui permet de contrôler la direction et la vitesse d’un moteur DC de manière sécurisée, sans connecter directement le moteur à l’ESP32. Ce projet est adapté aux débutants et aux makers intermédiaires souhaitant apprendre le contrôle des moteurs avec l’ESP32 et peut être facilement étendu à des projets de robotique ou d’automatisation.

Supplies

-----------------------------------------------------------------------

  1. ESP32 development board
  2. 30 pin esp32 expansion board
  3. USB-A to Micro-USB cable
  4. 6V DC motor
  5. L298N motor driver module
  6. 4 × 1.5 V AA batteries
  7. AA battery holder
  8. Jumper wires

-----------------------------------------------------------------------

  1. Carte de développement ESP32
  2. Carte d'extension ESP32 à 30 broches
  3. Câble USB-A vers micro-USB
  4. Moteur à courant continu (MCC) 6V
  5. Module driver de moteur L298N
  6. 4 piles AA de 1,5 V
  7. Support de piles AA
  8. Fils de connexion

----------------------------------------------------------------------

Step 1: L298N Working Principle / Principe De Fonctionnement Du L298N

The L298N is a dual H-bridge motor driver that allows a microcontroller, such as the ESP32, to safely control a DC motor without connecting it directly to the motor’s power supply. It uses two digital input pins (IN1 and IN2) to control the rotation direction of the motor. When IN1 is HIGH and IN2 is LOW, the motor rotates in one direction; when IN1 is LOW and IN2 is HIGH, the motor rotates in the opposite direction.

The ENA (Enable) pin is used to enable or disable the motor channel and can also be used to control the motor speed using PWM. By default, the L298N module includes a jumper connected to the ENA pin, which ties it to 5V, meaning the motor is always enabled and runs at full speed. If speed control is required, this jumper must be removed, and the ENA pin should be connected to a PWM-capable pin on the ESP32. This allows precise speed control while keeping the direction control managed by IN1 and IN2.

Power Pins

  1. 12V (VCC / +Vmotor): Motor power supply input (usually 6–12 V, depending on the motor).
  2. 5V: Logic power supply. This pin can output 5 V if the onboard regulator is enabled (jumper installed), or it can be used as an input if the jumper is removed.
  3. GND: Ground. Must be connected to the ESP32 GND.

Motor Output Pins

  1. OUT1 & OUT2: Outputs for Motor A.
  2. OUT3 & OUT4: Outputs for Motor B.

Control Pins (Logic Inputs)

  1. IN1 & IN2: Control the direction of Motor A.
  2. IN1 = HIGH, IN2 = LOW → Motor A rotates in one direction
  3. IN1 = LOW, IN2 = HIGH → Motor A rotates in the opposite direction
  4. IN3 & IN4: Control the direction of Motor B (same logic).

Enable Pins

  1. ENA: Enable pin for Motor A.
  2. HIGH → Motor enabled
  3. LOW → Motor stopped
  4. Can receive a PWM signal to control speed
  5. ENB: Enable pin for Motor B (same behavior).

Jumpers

  1. ENA / ENB Jumpers:
  2. By default, a jumper connects ENA/ENB to 5 V, meaning the motor is always enabled at full speed.
  3. To control the motor speed using PWM, remove the jumper and connect ENA or ENB to a PWM-capable pin on the ESP32.

https://www.st.com/resource/en/datasheet/l298.pdf

-------------------------------------------------------------------------------------------

Le L298N est un module pilote de moteurs basé sur un double pont en H, ce qui lui permet de contrôler le sens de rotation d’un moteur à courant continu. Les broches IN1 et IN2 déterminent la direction du moteur : selon leur état logique (HIGH ou LOW), le moteur tourne dans un sens ou dans l’autre, ou s’arrête. Le module dispose également d’une broche ENA (Enable) qui permet d’activer ou de désactiver le moteur. Par défaut, un jumper est installé sur la broche ENA, ce qui la relie directement au 5 V et active le moteur en permanence à pleine vitesse. Si l’on souhaite contrôler la vitesse du moteur, il faut retirer ce jumper et connecter la broche ENA à une sortie de la carte ESP32, afin d’y appliquer un signal PWM. Cela permet de faire varier la vitesse du moteur tout en conservant un contrôle sûr et fiable.

Broches d’alimentation

  1. 12V (VCC / +Vmotor) : entrée d’alimentation du moteur (généralement entre 6 et 12 V, selon le moteur utilisé).
  2. 5V : alimentation logique du module. Cette broche peut fournir du 5 V si le régulateur interne est activé (jumper présent), ou être utilisée comme entrée 5 V si le jumper est retiré.
  3. GND : masse. Doit obligatoirement être reliée au GND de l’ESP32 (masse commune).

Broches de sortie moteur

  1. OUT1 & OUT2 : sorties pour le moteur A.
  2. OUT3 & OUT4 : sorties pour le moteur B.

Broches de commande (Entrées logiques)

  1. IN1 & IN2 : contrôlent le sens de rotation du moteur A.
  2. IN1 = HIGH et IN2 = LOW → le moteur tourne dans un sens
  3. IN1 = LOW et IN2 = HIGH → le moteur tourne dans le sens opposé
  4. IN3 & IN4 : contrôlent le sens de rotation du moteur B (même principe).

Broches Enable

  1. ENA : broche d’activation du moteur A.
  2. HIGH → moteur activé
  3. LOW → moteur arrêté
  4. Peut recevoir un signal PWM pour contrôler la vitesse
  5. ENB : broche d’activation du moteur B (fonctionnement identique).

Jumpers (Cavaliers)

  1. Jumpers ENA / ENB :
  2. Par défaut, un jumper relie ENA/ENB au 5 V, ce qui signifie que le moteur est toujours activé à pleine vitesse.
  3. Pour contrôler la vitesse avec le PWM, il faut retirer le jumper et connecter ENA ou ENB à une broche PWM de l’ESP32.

https://www.st.com/resource/en/datasheet/l298.pdf

Step 2: Circuit Diagram and Source Code / Schéma Et Code Source

You can find the full source code below:

Step 3: Using ESP32 LEDC PWM Functions / Utilisation Des Fonctions PWM (LEDC) De L’ESP32

On the ESP32, motor speed control is achieved using hardware PWM through the LEDC functions. The function ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RESOLUTION) is used to configure a PWM channel by defining the channel number, the PWM signal frequency (for example 1000 Hz, which is suitable for DC motors), and the resolution (for example 8 bits, which provides a range of values from 0 to 255). Next, the function ledcAttachPin(ENA, PWM_CHANNEL) links this PWM (Pulse Width Modulation) channel to a physical ESP32 pin, in this case the ENA pin of the L298N, allowing the voltage applied to the motor to be modulated. Finally, the function ledcWrite(PWM_CHANNEL, value) sets the PWM duty cycle: a value of 0 stops the motor, a medium value makes the motor rotate slowly, and a value close to 255 corresponds to maximum speed. Thanks to these functions, the ESP32 can control the motor speed accurately and efficiently without changing the power supply voltage.

-------------------------------------------------------------------------------------------

Sur l’ESP32, le contrôle de la vitesse d’un moteur se fait grâce au PWM matériel via les fonctions ledc. La fonction ledcSetup(PWM_CHANNEL, PWM_FREQ, PWM_RESOLUTION) permet de configurer un canal PWM en définissant son numéro de canal, la fréquence du signal PWM (par exemple 1000 Hz, adaptée aux moteurs DC) et la résolution (par exemple 8 bits, ce qui donne une plage de valeurs de 0 à 255). Ensuite, la fonction ledcAttachPin(ENA, PWM_CHANNEL) associe ce canal PWM à une broche physique de l’ESP32, ici le pin ENA du L298N, ce qui permet de moduler la tension appliquée au moteur. Enfin, la fonction ledcWrite(PWM_CHANNEL, value) permet de définir le rapport cyclique du PWM : une valeur de 0 arrête le moteur, une valeur intermédiaire fait tourner le moteur lentement, et une valeur proche de 255 correspond à la vitesse maximale. Grâce à ces fonctions, l’ESP32 peut contrôler la vitesse du moteur de manière précise et efficace sans modifier la tension d’alimentation.

Step 4: Installing ESP32 in Arduino IDE / Installation De L'ESP32 Dans L'IDE De L'arduino

1- Open Arduino IDE, then go to File> Preferences

2- Enter the following into the “Additional Board Manager URLs” field:

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

Then, click the “OK” button.

-------------------------------------------------------------------------------------------

1- Ouvrir l’Arduino IDE, puis va dans File> Preferences.

2- Dans le champ “Additional Board Manager URLs”, saisir l’adresse suivante :

https://raw.githubusercontent.com/espressif/arduino-esp32/gh-pages/package_esp32_index.json

Ensuite, cliquer sur le bouton "OK".

Step 5: Libraries / Bibliothèques

1- Open Arduino IDE, then go to the Board Manager. In the search bar, install the “ESP32 by Espressif Systems” library.

2- Once the installation is complete, add and select the ESP32 board you are using from the Tools > Boards menu.

3- On your computer, open the Device Manager to check which COM port your ESP32 board is connected to.

4- Go back to Arduino IDE, navigate to Tools > Port, and select the COM port corresponding to your board.

-------------------------------------------------------------------------------------------

1- Ouvrir Arduino IDE, puis accéder au Gestionnaire de cartes (Board Manager). Dans la barre de recherche, installer la bibliothèque “ESP32 by Espressif Systems”.

2- Une fois l’installation terminée, ajouter et sélectionner la carte ESP32 que vous utilisez dans le menu Tools > Boards

3- Sur l’ordinateur, ouvrir le Gestionnaire de périphériques (Device Manager) pour vérifier sur quel port COM est connectée la carte ESP32.

4- Revenir dans Arduino IDE, aller dans Tools > Port et sélectionner le port COM correspondant à la carte.

Step 6: Erreur : “Wrong Boot Mode Detected (0x13)! the Chip Needs to Be in Download Mode.”

When you compile your program to upload it, you might encounter the error:

“A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0x13)! The chip needs to be in download mode.”

The solution is simple:

1- Click Upload in the Arduino IDE.

2- When you see:


Connecting...

3- Hold down the BOOT button on your ESP32.

4- Release the BOOT button when your program is uploaded successfully to the board.

Important note: even after fixing this error, the program may still fail to start immediately. If that happens, simply press the RESET button on the ESP32 to get it working properly.

-------------------------------------------------------------------------------------------

Lorsque vous compilez votre programme pour le téléverser, vous pouvez rencontrer l’erreur :

“A fatal error occurred: Failed to connect to ESP32: Wrong boot mode detected (0x13)! The chip needs to be in download mode.”

La solution est simple :

1- Cliquez sur Upload dans Arduino IDE.

2- Lorsque vous voyez :


Connecting...

3- Maintenez le bouton BOOT de votre ESP32.

4- Relâchez le bouton BOOT quand votre programme est téléversé correctement sur la carte.

Remarque importante : même lorsque cette erreur est résolue, il peut arriver que le programme ne démarre pas directement. Dans ce cas, il suffit d’appuyer sur le bouton RESET de l’ESP32 pour que tout fonctionne correctement.

Step 7: Error: ‘ledcSetup’ Was Not Declared in This Scope

When compiling the code for the ESP32, you may encounter the error : ‘ledcSetup’ was not declared in this scope. This issue is usually related to the version of the ESP32 core installed in the Arduino IDE. Some recent versions of the ESP32 package can cause incompatibilities with certain PWM functions. To fix this problem, open the Boards Manager in the Arduino IDE, search for “ESP32 by Espressif Systems”, and install or downgrade to version 2.0.14, which is stable and fully compatible with the ledcSetup, ledcAttachPin, and ledcWrite functions. After installing the correct version, it is recommended to restart the Arduino IDE and then recompile the program.

-------------------------------------------------------------------------------------------

Lors de la compilation du code avec l’ESP32, il est possible de rencontrer l’erreur : 'ledcSetup' was not declared in this scope. Cette erreur est généralement liée à la version du package ESP32 installée dans l’Arduino IDE. Certaines versions récentes du core ESP32 peuvent provoquer des incompatibilités avec certaines fonctions PWM. Pour résoudre ce problème, il suffit d’ouvrir le Boards Manager dans l’Arduino IDE, de rechercher “ESP32 by Espressif Systems”, puis d’installer ou de revenir à la version 2.0.14, qui est stable et compatible avec les fonctions ledcSetup, ledcAttachPin et ledcWrite. Après l’installation, il est recommandé de redémarrer l’Arduino IDE, puis de recompiler le programme.