ESP32 Bluetooth Control Motors

Hello friends, I have a problem with an ESP32, I have two model Metal Gearbox Para Smart Car Robot(130RPM) motors connected to an ESP32 and a raspberry pi that acts as an on-board computer. As a system requirement, Bluetooth communication must be used between both systems.
The problem is that when I have the ESP32 without connecting to the motors it receives and executes the orders (seen by the console it executes the Serial.println) but if I connect the ESP32 to the motor control board it starts to have a very significant delay, in On certain occasions it does carry out the orders on time (assuming the delay of Bluetooth technology) but sometimes it gets stuck on one of the sent orders.
If someone can give me a hand and if they have any idea how to solve the error. If I'm not wrong, I think the fault is in the motor control.
NOTE: the ESP32 program uses multitasking because it was one of the solutions I tried, but it didn't work

#include <Arduino.h>
#include <BluetoothSerial.h>  //libreria Bluetooth
#include <TaskScheduler.h> //libreria del planificador

//***********************************
//      INICIALIZACION BLUETOOTH
//***********************************
BluetoothSerial SerialBT;
String comando;   //comando con la instrucción del robot

//***********************************
//    DEFICION DE FUNCIONES
//***********************************
void  recibe_comandos();
void  mueve_motores();

//***********************************
//    INICIAR MULTITAREA
//***********************************
Scheduler planificador; //definicion del planificador
  //Task [nombre_tarea]([tiempo mseg],[veces ejecuta],[funcion ejecuta],[nombre planificador],[bol]);
Task comandoBT(500,TASK_FOREVER,&recibe_comandos,&planificador,true);
Task motores(500,TASK_FOREVER,&mueve_motores,&planificador,true);
  

//***********************************
//    TAREAS PRINCIPALES
//***********************************
void recibe_comandos(){   //funcion que recibe comandos por Bluetooth desde la Raspberry Pi
  if (SerialBT.available()) {
    //serial.isempty 
    //While me llegue algo lo meto en una variable
    //fuera del while son todos if
    comando = SerialBT.readString();
    Serial.println(comando);
  }//if (SerialBT.available())
}//recibe_comandos()

void mueve_motores(){     //funcion que realiza movimiento de los motores
//    switch (comando) {
//      case 'f':
//        moving_fordward();
//        Serial.println("Adelante");
//        delay(10);
//        break;
//      case 'b':
//        moving_backward();
//        Serial.println("Atras");
//        delay(10);
//        break;
//      case 's':
//      stop_motors();
//      Serial.println("Stop");
//      delay(10);
//      break;  
//      case 'r':
//      move_right();
//      Serial.println("Stop");
//      delay(10);
//      break;  
//      case 'l':
//      move_left();
//      Serial.println("Izquierda");
//      delay(10);
//      break;  
//    }//switch (comando) 
    
  if (comando == "f"){    //no necesito el \n
      moving_fordward();
      Serial.println("Adelante");
      //delay(10);
    } else if (comando == "b"){
      moving_backward();
      //Serial.println("Atras");
      delay(10);
    }  else if (comando == "s"){
      stop_motors();
      Serial.println("Stop");
      //delay(10);
    } else if (comando == "r"){
      move_right();
      Serial.println("Derecha");
      //delay(10);
    } else if (comando == "l"){
       move_left();  
       Serial.println("Izquierda");
       //delay(10);
    }else{
      Serial.println('.');
    }//if-else - movimiento
}//mueve_motores()

// ********CONTROL DE MOTORES**********
// Motor1 - Derecha
int motorDchaPin1 = 18; 
int motorDchaPin2 = 19; 
int enableMotorDcha = 5; 

// Motor2 - Izquierda
int motorIzqPin1 = 27; 
int motorIzqPin2 = 26; 
int enableMotorIZq = 14; 

int speedmotors = 200;  //velocidad de los motores (0-255)

void setup() {
  Serial.begin(115200);
  
  //Inicializacion de pines de salida:
  pinMode(motorDchaPin1, OUTPUT);
  pinMode(motorDchaPin2, OUTPUT);
  pinMode(enableMotorDcha, OUTPUT);
  pinMode(motorIzqPin1, OUTPUT);
  pinMode(motorIzqPin2, OUTPUT);
  pinMode(enableMotorIZq, OUTPUT);
  
  //inicializacion de motores
  analogWrite(enableMotorDcha, speedmotors);  //establezco la velocidad inicial - motorDcha
  analogWrite(enableMotorIZq, speedmotors);  //establezco la velocidad inicial - motorIzq

  SerialBT.begin("ESP32");  // Inicializa el módulo Bluetooth con el nombre "ESP32"
  
}//setup

// ********************************
//  FUNCIONES DE CONTROL DE MOTORES
// ********************************

void loop() {
  //ejecucion del planificador
  planificador.execute();
}//loop

// ************************************
//  FUNCIONES DE CONTROL DE MOTORES
// ************************************
void moving_fordward(){
  digitalWrite(motorDchaPin1, LOW);
  digitalWrite(motorDchaPin2, HIGH);
  digitalWrite(motorIzqPin1, LOW);
  digitalWrite(motorIzqPin2, HIGH); 

  analogWrite(enableMotorDcha, speedmotors);  //establezco la velocidad motorDcha
  analogWrite(enableMotorIZq, speedmotors);  //establezco la velocidad motorIzq
}//moving_fordward()

void moving_backward(){
  digitalWrite(motorDchaPin1, HIGH);
  digitalWrite(motorDchaPin2, LOW); 
  digitalWrite(motorIzqPin1, HIGH);
  digitalWrite(motorIzqPin2, LOW);
  
  analogWrite(enableMotorDcha, speedmotors);  //establezco la velocidad motorDcha
  analogWrite(enableMotorIZq, speedmotors);  //establezco la velocidad motorIzq
}//moving_backward()

void stop_motors(){
  digitalWrite(motorDchaPin1, LOW);
  digitalWrite(motorDchaPin2, LOW);
  digitalWrite(motorIzqPin1, LOW);
  digitalWrite(motorIzqPin2, LOW);  
  //NOTA: no necesito establecer velocidad a los motores
}//stop_motors()

void move_right(){
  digitalWrite(motorDchaPin1, LOW);
  digitalWrite(motorDchaPin2, HIGH); 
  digitalWrite(motorIzqPin1, HIGH);
  digitalWrite(motorIzqPin2, LOW); 
  
  // Gira el motor izquierdo a una velocidad mayor que el motor derecho
  analogWrite(enableMotorDcha, speedmotors/2);  //establezco la velocidad motorDcha
  analogWrite(enableMotorIZq, speedmotors/4);  //establezco la velocidad motorIzq
}//move_rigth()

void move_left(){
  digitalWrite(motorDchaPin1, HIGH);
  digitalWrite(motorDchaPin2, LOW); 
  digitalWrite(motorIzqPin1, LOW);
  digitalWrite(motorIzqPin2, HIGH); 
  
  // El motor que gira hacia atras lo hace a una velocidad menor
  analogWrite(enableMotorDcha, speedmotors/4);  //establezco la velocidad motorDcha
  analogWrite(enableMotorIZq, speedmotors/2);  //establezco la velocidad motorIzq
}//move_left()

It sounds like you have power supply problems. Interference from electrical noise generated by the motors or voltage drops due to an inadequate and/or poorly decoupled power supply causes MCUs to reset or behave erratically.

Please post a complete wiring diagram, (hand drawn is preferred), with pins and connections clearly labeled. Also post links to the motors and motor drivers.

Hello friends, I have a problem with an ESP32, I want to connect 2 PING ultrasonic sensors, 2 vl0x53 ToF sensors and an IMU as you can see in the following code. The problem is that the second of the ultrasonic sensors always reads 0 and I cannot find the fault

/**********************************
 * SENSOR DE ULTRASONIDOS - PING
 *********************************/
//variable declarations
long duration1;
int distance1;

long duration2;
int distance2;

const int ultrasonic1 = 12;
const int ultrasonic2 = 27;

/*****************************
 * IMU - ICM20948
 ****************************/
#include <Adafruit_ICM20X.h>
#include <Adafruit_ICM20948.h>
#include <Adafruit_Sensor.h>
#include <Wire.h>     //SCL->22   SDA->21

Adafruit_ICM20948 icm;
uint16_t measurement_delay_us = 65535; // Delay between measurements for testing

float temperatura;
int acelX;
int acelY;
int acelZ;
int gyroX;
int gyroY;
int gyroZ;

/*****************************
 * ToF - VL53L0X
 ****************************/
#include "Adafruit_VL53L0X.h"

// address we will assign if dual sensor is present
#define LOX1_ADDRESS 0x30
#define LOX2_ADDRESS 0x31

// set the pins to shutdown
#define SHT_LOX1 19
#define SHT_LOX2 18

Adafruit_VL53L0X lox1 = Adafruit_VL53L0X();
Adafruit_VL53L0X lox2 = Adafruit_VL53L0X(); 
// this holds the measurement
VL53L0X_RangingMeasurementData_t measure1;
VL53L0X_RangingMeasurementData_t measure2;

int tof1;
int tof2;

/*****************************
 * ENVIO DE DATOS POR SERIAL 
 ****************************/
String string1;

void setup() {
  Serial.begin(115200);
  
  Wire.begin();   //INICIALIZO EL BUS I2C EN LOS PINES SDA->21, SCL->22
  
  //******** ULTRASONIDOS *****************
  pinMode(ultrasonic1, OUTPUT);
  digitalWrite(ultrasonic1, LOW); 

  pinMode(ultrasonic2, OUTPUT);
  digitalWrite(ultrasonic2, LOW);
  //Serial.println("Ultrasonic OK");
  //******** IMU *****************
  icm.begin_I2C();
  icm.setAccelRange(ICM20948_ACCEL_RANGE_16_G);
  icm.setGyroRange(ICM20948_GYRO_RANGE_2000_DPS);
  uint16_t accel_divisor = icm.getAccelRateDivisor();
  float accel_rate = 1125 / (1.0 + accel_divisor);
  //  icm.setGyroRateDivisor(255);
  uint8_t gyro_divisor = icm.getGyroRateDivisor();
  float gyro_rate = 1100 / (1.0 + gyro_divisor);
  icm.setMagDataRate(AK09916_MAG_DATARATE_10_HZ);
  //Serial.println("IMU OK");
  //******** ToF *****************
  pinMode(SHT_LOX1, OUTPUT);
  pinMode(SHT_LOX2, OUTPUT);
    //Shutdown pins inited...
  digitalWrite(SHT_LOX1, LOW);
  digitalWrite(SHT_LOX2, LOW);
    //Both in reset mode...(pins are low) COMIENZO EL SET ID
  
  // all reset
  digitalWrite(SHT_LOX1, LOW);    
  digitalWrite(SHT_LOX2, LOW);
  delay(10);
  // all unreset
  digitalWrite(SHT_LOX1, HIGH);
  digitalWrite(SHT_LOX2, HIGH);
  delay(10);
  
  // activating LOX1 and resetting LOX2
  digitalWrite(SHT_LOX1, HIGH);
  digitalWrite(SHT_LOX2, LOW);

  lox1.begin(LOX1_ADDRESS);  // initing LOX1

  digitalWrite(SHT_LOX2, HIGH); // activating LOX2
  delay(10);

  lox2.begin(LOX2_ADDRESS);  // initing LOX2
  //Serial.println("ToF OK");
}

void loop() {
  //******** ULTRASONIDOS *****************
  //Trigger the sensor with a 2usec HIGH pulse
  digitalWrite(ultrasonic1, HIGH);
  digitalWrite(ultrasonic2, HIGH);
  delayMicroseconds(2);
  digitalWrite(ultrasonic1, LOW);
  digitalWrite(ultrasonic2, LOW);
  pinMode(ultrasonic1, INPUT);
  pinMode(ultrasonic2, INPUT);
  duration1 = pulseIn(ultrasonic1, HIGH);
  distance1 = duration1*0.034/2;
  duration2 = pulseIn(ultrasonic2, HIGH);
  distance2 = duration2*0.034/2;
  delay(200);
  pinMode(ultrasonic1, OUTPUT);
  digitalWrite(ultrasonic1, LOW);
  pinMode(ultrasonic2, OUTPUT); 
  digitalWrite(ultrasonic2, LOW);
  
  //******** IMU *****************
  //  /* Get a new normalized sensor event */
  sensors_event_t accel;
  sensors_event_t gyro;
  sensors_event_t mag;
  sensors_event_t temp;
  icm.getEvent(&accel, &gyro, &temp, &mag);

  temperatura=temp.temperature;   //obtengo temperatura
  
  acelX=accel.acceleration.x;     //obtengo la aceleración del eje X
  acelY=accel.acceleration.y;     //obtengo la aceleración del eje Y
  acelZ=accel.acceleration.z;     //obtengo la aceleración del eje Z

  //magX=mag.magnetic.x;
  //magY=mag.magnetic.y;
  //magZ=mag.magnetic.z;

  gyroX=gyro.gyro.x* 57.3;              //angulo de giro del eje X
  gyroY=gyro.gyro.y* 57.3;              //angulo de giro del eje Y
  gyroZ=gyro.gyro.z* 57.3;              //angulo de giro del eje Z
        //NOTA: hago la conversion de rad/s a deg/s  
  //******** ToF *****************
  lox1.rangingTest(&measure1, false); // pass in 'true' to get debug data printout!
  lox2.rangingTest(&measure2, false); // pass in 'true' to get debug data printout!
  tof1=measure1.RangeMilliMeter/10;   //medida en mm pasado a cm
  tof2=measure2.RangeMilliMeter/10;   //medida en mm pasado a cm

  //******** Salida Por Serial *****************
  string1 = "Distancia1: " + String(distance1) + ", Distancia2: " + String(distance2) + ", Temperatura: " + String(temperatura) + ", AcelX: " + String(acelX) + ", AcelY: " + String(acelY) + ", AcelZ: " + String(acelZ) + ", giroX: " + String(gyroX) + ", giroY: " + String(gyroY) + ", giroZ: " + String(gyroZ)+ ", ToF1: " + String(tof1)+ ", ToF2: " + String(tof2);
  //string1 = "Distancia1:" + distance1 + ",Distancia2:" + distancia2 + ",Temperatura:" + temperatura + ",AcelX:" + acelX + ",AcelY:" + acelY + ",AcelZ:" + acelZ + ",giroX" + gyroX + ",giroY" + gyroY + ",giroZ:" + gyroZ;

  Serial.println(string1);
  delay(1000);
}

Adresses are correct?

Two ultrasonic sensors will interfere with each other, if triggered at the same time. Trigger them separately, with a delay to allow echos from the first to fade away, before triggering the second.

But first, make sure that the sensor2 works by itself, with nothing else connected.

There's your problem.
Not so much sensors interfering with one another - which they do, given a chance - but pulseIn() is blocking, so the second pulseIn() is started only after the first pulse has finished - and likely the second has finished, too, so all it does is wait a full second (the default timeout) for nothing to come in.

@jairotd25,

Your two or more topics on the same or similar subject have been merged.

Please do not duplicate your questions as doing so wastes the time and effort of the volunteers trying to help you as they are then answering the same thing in different places.

Please create one topic only for your question and choose the forum category carefully. If you have multiple questions about the same project then please ask your questions in the one topic as the answers to one question provide useful context for the others, and also you won’t have to keep explaining your project repeatedly.

Repeated duplicate posting could result in a temporary or permanent ban from the forum.

Could you take a few moments to Learn How To Use The Forum

It will help you get the best out of the forum in the future.

Thank you.

1 Like

Hi, the motors are: https://naylampmechatronics.com/motores-dc/616-motor-dc-jga25-370-12v350rpm-con-encoder.html and the driver: https://www.amazon.es/OcioDual-Controlador-Motores-Driver-Stepper/dp/B07YNR5KWP/ref=asc_df_B07YNR5KWP/?tag=googshopes-21&linkCode=df0&hvadid=628580889748&hvpos=&hvnetw=g&hvrand=9997982707626421357&hvpone=&hvptwo=&hvqmt=&hvdev=c&hvdvcmdl=&hvlocint=&hvlocphy=9047040&hvtargid=pla-1875528526707&psc=1&mcid=2dd5ec2bd06b31b1b2530a5372fad446
I have tried to connect with the Raspberry Pi via serial and the communication is almost instantaneous, I have also eliminated the function calls, and executed the instructions directly, although I think it is not the most optimal, could it also be a reason for delay, right?

The connection made is very similar to the one in the following image

It sounds reasonable, but how can I solve it?

It is pointless to post a picture of someone else's wiring diagram.

Please post a correct, hand drawn wiring diagram of your circuit, with pins and connections clearly labeled.

That should be obvious based on the explanation (and you hopefully understanding what's going on in both the Arduino and the sensor): trigger and read one, then trigger and read the other.

This topic was automatically closed 180 days after the last reply. New replies are no longer allowed.