Cerca codice

Come controllare i motori CC con un modulo ESP32 e L298N tramite Wi-Fi

Come controllare i motori CC con un modulo ESP32 e L298N tramite Wi-Fi

Controlla due motori DC tramite Wi-Fi con ESP32 e L298N

Questo tutorial dimostra come costruire un potente e reattivo sistema per controllare due motori DC utilizzando un microcontrollore ESP32 e un modulo driver motore L298N. Sarai in grado di avviare, fermare, cambiare la velocità e invertire la direzione di ciascun motore in modo indipendente tramite una pagina web ospitata dall'ESP32. Questa interfaccia web può essere utilizzata da qualsiasi dispositivo con un browser web, come un telefono o un computer, purché sia connesso alla stessa rete Wi-Fi.


Panoramica dei componenti

  • ESP32:Un potente microcontrollore con Wi-Fi integrato, perfetto per progetti di controllo basati sul web.
  • Driver per motori L298N:Un driver per motori dual H-bridge versatile ed economico, in grado di controllare due motori DC. Può gestire un'ampia gamma di tensione, fino a 35 volt, rendendolo adatto alla maggior parte dei motori per hobbisti utilizzati in auto intelligenti e robotica.
  • Robojax Library:Per semplificare il codice, utilizziamo una libreria personalizzata Robojax progettata per il driver L298N che funziona con l'ESP32.

Guida all'impianto elettrico

Il cablaggio per questo progetto collega l'ESP32 al driver L298N, che a sua volta si collega ai motori e a una fonte di alimentazione. Il cablaggio completo è spiegato nel video a partire da05:05.

Collegamenti Elettrici

  • Alimentazione esterna:Collega l'alimentazione del motore (ad es., 7,2V a 35V) ai terminali a vite dell'L298N. Il filo positivo va al terminale `+12V` (o VMS), e il filo negativo va al terminale `GND`.
  • Alimentare l'ESP32:Il modulo L298N ha un regolatore di tensione integrato da 5V. Una volta fornita l'alimentazione esterna, questo regolatore genera un 5V stabile, che è disponibile al terminale `+5V`. Puoi usarlo per alimentare il tuo ESP32 collegando un filo dal terminale `+5V` del L298N al pin `5V` (o Vin) dell'ESP32. Questo elimina la necessità di un'alimentazione separata per il microcontrollore.
  • Terreno comune:È essenziale avere un terreno comune. Collega un filo dal terminale `GND` dell'L298N a un pin `GND` sull'ESP32.

Collegamenti dei pin di controllo

Collegare i sei pin di controllo dell'L298N all'ESP32 come segue. Questi pin controllano la velocità e la direzione dei due motori.

  • Motore 1 (Lato A L298N):
    • `ENA` si connette a ESP32pin 19(Controllo della Velocità)
    • `IN1` si collega a ESP32pin 18(Controllo Direzionale)
    • `IN2` si collega a ESP32pin 5(Controllo Direzione)
  • Motore 2 (L298N Lato B):
    • `ENB` si collega a ESP32pin 4(Controllo della velocità)
    • `IN3` si connette a ESP32pinna 17(Controllo della direzione)
    • `IN4` si connette a ESP32pin 16(Controllo Direzionale)

Configurazione di Arduino IDE e librerie

Prima di caricare il codice, è necessario preparare il tuo Arduino IDE per lavorare con l'ESP32. Il processo di configurazione è dettagliato nel video a07:41.

Il link da utilizzare nelle "preferenze" dell'IDE Arduino per la scheda ESP32 è:
https://dl.espressif.com/dl/package_esp32_index.json Guarda il video per le istruzioni.

  1. Aggiungi URL della scheda ESP32:Vai su File > Preferenze. Nel campo "URL aggiuntivi per il gestore di schede", devi incollare l'URL JSON ufficiale per le schede ESP32.
  2. Installa le schede ESP32:Apri il Gestore Schede (Strumenti > Scheda > Gestore Schede), cerca "esp32" e installa il pacchetto fornito da Espressif Systems.
  3. Seleziona Scheda e Porta:Vai su Strumenti > Scheda e seleziona una scheda adatta come "Modulo Rover ESP32". Quindi, vai su Strumenti > Porta e seleziona la porta COM a cui è collegato il tuo ESP32. Puoi trovare il numero della porta corretto nel Gestore dispositivi del tuo computer.
  4. Installa la libreria Robojax:Devi scaricare la libreria Robojax L298N, che sarà disponibile come file .zip. Nell'IDE di Arduino, vai su Sketch > Includi Libreria > Aggiungi Libreria .ZIP... e seleziona il file scaricato per installarlo.

Impostazioni del codice personalizzabili dall'utente

Il codice fornito è progettato per essere facile da usare. Devi solo configurare alcuni parametri nella parte superiore del file per adattarli alla tua configurazione e preferenze. Questo è spiegato a partire da12:20.

Credenziali Wi-Fi

Devi cambiare queste due righe per farle corrispondere al nome (SSID) e alla password della tua rete Wi-Fi locale. Ricorda che l'SSID è sensibile alle maiuscole.

const char *ssid = "YourWifiName";
const char *password = "YourWifiPassword";

Inizializzazione della Libreria (Modalità Debug)

Il codice offre due opzioni per inizializzare la libreria. Per la risoluzione dei problemi, puoi abilitare la modalità di debug, che stampa informazioni dettagliate sullo stato al Monitor Seriale. Per il funzionamento normale, utilizza la riga senza debug per risparmiare risorse. Per passare da una all'altra, basta commentare una riga e decommentare l'altra.

// for two motors without debug information
//Robojax_L298N_DC_motor motor(IN1, IN2, ENA, CHA, IN3, IN4, ENB, CHB);

// for two motors with debug information
Robojax_L298N_DC_motor motor(IN1, IN2, ENA, CHA, IN3, IN4, ENB, CHB, true);

Parametri del Comportamento Motorio

Puoi impostare il comportamento predefinito per ciascun motore in modo indipendente.

// MOTOR 1 SETTINGS
int       motor1Direction = CW; // Default direction: CW or CCW
const int motor1changeStep = 10; // Speed change per click (e.g., 10%)
int       motor1Speed = 40; // Initial speed when the page loads (0-100)
const int motor1MinimumSpeed = 20; // The minimum speed the motor will run at
const int motor1MaximumSpeed = 100; // The maximum speed the motor will run at
int       motor1StopState = HIGH; // Motor state on load: HIGH=Stopped, LOW=Running

// MOTOR 2 SETTINGS
int       motor2Direction = CW;
const int motor2changeStep = 10;
int       motor2Speed = 60;
const int motor2MinimumSpeed = 20;
const int motor2MaximumSpeed = 100;
int       motor2StopState = HIGH;

Progetto dal Vivo in Azione

Dopo aver caricato il codice, apri il Monitor Serial di Arduino e premi il pulsante di reset sull'ESP32. L'ESP32 si connetterà al tuo Wi-Fi e stamperà il suo indirizzo IP.

Digita questo indirizzo IP nel browser di un telefono o computer che è connesso alla stessa rete Wi-Fi. La pagina di controllo si caricherà, mostrando i controlli per entrambi i motori. Puoi usare i pulsanti per aumentare o diminuire la velocità, cambiare direzione e avviare o fermare ciascun motore. L'interfaccia web si aggiornerà in tempo reale per mostrare lo stato attuale (velocità, direzione e stato in funzione/fuori funzione) di ciascun motore.


Timestamp video

  • 00:00- Introduzione e dimostrazione finale del progetto
  • 02:02- Panoramica del modulo L298N
  • 05:05- Guida all'impianto elettrico
  • 07:41- Configurazione dell'IDE Arduino per ESP32
  • 09:49- Installazione della Biblioteca Robojax
  • 12:20- Spiegazione delle impostazioni del codice personalizzabili dall'utente
  • 22:46- Dimostrazione del Progetto Live

Immagini

Motore CC con ESP32: configurazione principale
Motore CC con ESP32: configurazione principale
Moto DC con ESP32: Schermo di Controllo
Moto DC con ESP32: Schermo di Controllo
Motore DC con ESP32: Cablaggio a L298N
Motore DC con ESP32: Cablaggio a L298N
Motore DC con ESP32: Pagina di codice e vista dello schermo di controllo
Motore DC con ESP32: Pagina di codice e vista dello schermo di controllo
Motore DC con ESP32: Dimostrazione
Motore DC con ESP32: Dimostrazione
Motore DC con ESP32:Controllo del Motore DC Utilizzando il Telefono Cellulare
Motore DC con ESP32:Controllo del Motore DC Utilizzando il Telefono Cellulare
279-Arduino code to control DC Motors with ESP32 with L298N module over WiFi (two motors)
Lingua: C++
/*
 * To control DC Motors with ESP32 with L298N module over WiFi (two motors)
 * Motor is controlled using Robojax_L298N_DC_motor library
 * 
 * 
 * Watch video instruction for this code (with Wifi): https://youtu.be/Olq8NXgNySA
 * Watch video instruction for this code (without WiFi): https://youtu.be/gOMHU0Q8upA


 * Written by Ahmad Shamshiri on Dec 27, 2019
 * in Ajax, Ontario, Canada. www.robojax.com
 * 

 * Get this code and other Arduino codes from Robojax.com


or make a donation using PayPal http://robojax.com/L/?id=64

 *  * This code is "AS IS" without warranty or liability. Free to be used as long as you keep this note intact.* 
 * This code has been downloaded from Robojax.com
    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    This program is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program.  If not, see <https://www.gnu.org/licenses/>.
   Copyright (c) 2015, Majenko Technologies
   All rights reserved.

   Redistribution and use in source and binary forms, with or without modification,
   are permitted provided that the following conditions are met:

 * * Redistributions of source code must retain the above copyright notice, this
     list of conditions and the following disclaimer.

 * * Redistributions in binary form must reproduce the above copyright notice, this
     list of conditions and the following disclaimer in the documentation and/or
     other materials provided with the distribution.

 * * Neither the name of Majenko Technologies nor the names of its
     contributors may be used to endorse or promote products derived from
     this software without specific prior written permission.

   THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
   ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
   WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
   DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR
   ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
   (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
   LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
   ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
   (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
   SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <Robojax_L298N_DC_motor.h>
// motor 1 settings
#define CHA 0
#define ENA 19 // this pin must be PWM enabled pin if Arduino board is used
#define IN1 18
#define IN2 5

// motor 2 settings
#define IN3 17
#define IN4 16
#define ENB 4// this pin must be PWM enabled pin if Arduino board is used
#define CHB 1

const int CCW = 2; // do not change
const int CW  = 1; // do not change

#define motor1 1 // do not change
#define motor2 2 // do not change

// for single motor
//Robojax_L298N_DC_motor motor(IN1, IN2, ENA, CHA, true);  

// for two motors without debug information // Watch video instruction for this line: https://youtu.be/2JTMqURJTwg
//Robojax_L298N_DC_motor motor(IN1, IN2, ENA, CHA, IN3, IN4, ENB, CHB);/

// for two motors with debug information
Robojax_L298N_DC_motor motor(IN1, IN2, ENA, CHA, IN3, IN4, ENB, CHB, true);


int       motor1Direction = CW;//default direction of rotation
const int motor1changeStep = 10;// 10 is 10% every time button is pushed
int       motor1Speed = 40;// variable holding the light output value (initial value) 40 means 40%
const int motor1MinimumSpeed=20;
const int motor1MaximumSpeed=100;
int       motor1StopState=HIGH;//Stope state of motor (HIGH means STOP) and LOW means Start

int       motor2Direction = CW;//default direction of rotation
const int motor2changeStep = 10;// 10 is 10% every time button is pushed
int       motor2Speed = 60;// variable holding the light output value (initial value) 40 means 40%
const int motor2MinimumSpeed=20;
const int motor2MaximumSpeed=100;
int       motor2StopState=HIGH;//Stope state of motor (HIGH means STOP) and LOW means Start


#include "ESP32_L298N_DC_motor_wifi_page.h"


  
#include <WiFi.h>
#include <WiFiClient.h>
#include <WebServer.h>
#include <ESPmDNS.h>

const char *ssid = "Robojax";
const char *password = "YouTube2019_o_";

WebServer server(80);

const int led = 13;

void handleRoot() {
String HTML_page = motorControlHeader_1; 

 HTML_page.concat(".bar1 {width: " + String(motor1Speed)  + "%;}\n");
 //HTML_page.concat(motor1Speed);  
 //HTML_page.concat("%;}");
 HTML_page.concat(".bar2 {width: " + String(motor2Speed) + "%;}\n");
  
 HTML_page.concat(motorControlHeader_2);
  
 HTML_page.concat(motor1Control_p1);
   
 if(motor1Direction ==CW)
 {
      if(motor1StopState ==HIGH)
      {
        HTML_page.concat("<strong>Stopped - CW at ");
      }else{
        HTML_page.concat("<strong>Running - CW at ");        
      }
 }else{
      if(motor1StopState ==HIGH)
      {
        HTML_page.concat("<strong>Stopped - CCW at ");
      }else{
        HTML_page.concat("<strong>Running - CCW at ");        
      }  
 }
 HTML_page.concat(motor1Speed);
 HTML_page.concat(motor1Control_p2);
 if(motor1StopState ==HIGH)
 {
   HTML_page.concat("m1START\">START");
 }else{
   HTML_page.concat("m1STOP\">STOP"); 
 }
 HTML_page.concat(motor1Control_p3); 

///motor 2 begins
 HTML_page.concat(motor2Control_p1);
   
 if(motor2Direction ==CW)
 {
      if(motor2StopState ==HIGH)
      {
        HTML_page.concat("<strong>Stopped - CW at ");
      }else{
        HTML_page.concat("<strong>Running - CW at ");        
      }
 }else{
      if(motor2StopState ==HIGH)
      {
        HTML_page.concat("<strong>Stopped - CCW at ");
      }else{
        HTML_page.concat("<strong>Running - CCW at ");        
      }  
 }
 HTML_page.concat(motor2Speed);
 HTML_page.concat(motor2Control_p2);
 if(motor2StopState ==HIGH)
 {
   HTML_page.concat("m2START\">START");
 }else{
   HTML_page.concat("m2STOP\">STOP"); 
 }
 HTML_page.concat(motor2Control_p3); 
 
 HTML_page.concat("</body>\n</html>");
 
  server.send(200, "text/html", HTML_page);
}

void handleNotFound() {
  digitalWrite(led, 1);
  String message = "File Not Found\n\n";
  message += "URI: ";
  message += server.uri();
  message += "\nMethod: ";
  message += (server.method() == HTTP_GET) ? "GET" : "POST";
  message += "\nArguments: ";
  message += server.args();
  message += "\n";

  for (uint8_t i = 0; i < server.args(); i++) {
    message += " " + server.argName(i) + ": " + server.arg(i) + "\n";
  }

  server.send(404, "text/plain", message);
  digitalWrite(led, 0);
}

void setup(void) {
  Serial.begin(115200);
  motor.begin();
  //L298N DC Motor by Robojax.com

  WiFi.mode(WIFI_STA);
  WiFi.begin(ssid, password);
  Serial.println("");
  
    
  // Wait for connection
  while (WiFi.status() != WL_CONNECTED) {
    delay(500);
    Serial.print(".");
  }

  Serial.println("");
  Serial.print("Connected to ");
  Serial.println(ssid);
  Serial.print("IP address: ");
  Serial.println(WiFi.localIP());


  if (MDNS.begin("robojaxESP32")) {
    Serial.print("MDNS responder started at http://");
    Serial.println("robojaxESP32");
  }

  server.on("/", handleRoot);
  server.on("/speed", HTTP_GET, handleMotorSpeed);  
  server.on("/direction", HTTP_GET, handleMotorDirection); 
  server.on("/stop", HTTP_GET, handleMotorBrake);     
  server.onNotFound(handleNotFound);
  server.begin();
  Serial.println("HTTP server started"); 
}

void loop(void) {
  server.handleClient();


  if(motor1StopState ==HIGH)
  {
    motor.brake(motor1);  
    
  }else{
     motor.rotate(motor1, motor1Speed, motor1Direction);//run motor1 at motor1Speed% speed in motor1Direction 
  }
  
  if(motor2StopState ==HIGH)
  {
    motor.brake(motor2);  
    
  }else{
     motor.rotate(motor2, motor2Speed, motor2Direction);//run motor2 at motor2Speed% speed in motor2Direction 
  }

  delay(100);  
}


/*
 * handleMotorSpeed()
 * Slows down or speeds up the motor
 * returns nothing
 * Written by Ahmad Shamshiri on Dec 27, 2019
 * www.Robojax.com
 */
void handleMotorSpeed() {
  if(server.arg("do") == "m1slower" )
  {
    motor1Speed -=motor1changeStep;
    
      if(motor1Speed < motor1MinimumSpeed)
      {
        motor1Speed = motor1MinimumSpeed;
      }
  }else if(server.arg("do") == "m1faster")
  {
    motor1Speed +=motor1changeStep;   
     
      if(motor1Speed > motor1MaximumSpeed)
      {
        motor1Speed =motor1MaximumSpeed;
      } 
  }else if(server.arg("do") == "m2slower")
  {
    motor2Speed -=motor2changeStep;
    
      if(motor2Speed < motor2MinimumSpeed)
      {
        motor2Speed = motor2MinimumSpeed;
      }
  }else if(server.arg("do") == "m2faster")
  {
    motor2Speed +=motor2changeStep;   
     
      if(motor2Speed > motor2MaximumSpeed)
      {
        motor2Speed =motor2MaximumSpeed;
      } 
  }else{
    motor1Speed =0;   

  }

  handleRoot();
}//handleMotorSpeed() end

/*
 * handleMotorDirection()
 * changes the direction of the motor
 * returns nothing
 * Written by Ahmad Shamshiri on Dec 27, 2019
 * www.Robojax.com
 */
void handleMotorDirection() {
  if(server.arg("dir") == "m1CW")
  {
    motor1Direction =CW;

  }else if(server.arg("dir") == "m1CCW")
  {
    motor1Direction =CCW;

  }else if(server.arg("dir") == "m2CW")
  {
    motor2Direction =CW;

  }else{
    motor2Direction =CCW;   

  }

  handleRoot();
}//

/*
 * handleMotorBrake()
 * applies brake to the motor
 * returns nothing
 * Written by Ahmad Shamshiri on Dec 27, 2019
 * www.Robojax.com
 */
void handleMotorBrake() {
  if(server.arg("do") == "m1START")
  {  
      motor1StopState=LOW;
  }else if(server.arg("do") == "m1STOP")
  {  
      motor1StopState=HIGH;
  }else if(server.arg("do") == "m2START")
  {  
      motor2StopState=LOW;
  }else{
      motor2StopState=HIGH;    
  }
  handleRoot();
}//

File📁

Librerie Arduino (zip)

Altri file