Problemas con Arduino Duemilanove, Ping))) y controlador de motor Dual H-Bridge

¡Saludos!

En primer lugar, soy un novato y estoy aprendiendo, así que si digo alguna barbaridad no seaís crueles :stuck_out_tongue:

Estoy intentando montar un pequeño robot que gire cuándo detecte un obstáculo. Para ello utilizo un sensor de ultrasonidos Ping))), una placa Arduino Duemilanove y un controlador de motores Dual H-Bridge. Hasta ahora he conseguido que los motores funcionen sin problema y, independientemente, que el sensor Ping))) detecte objetos y me envíe la distancia por Serial a mi ordenador. He seguido tutoriales distintos para las dos cosas.

Ahora, lo que quiero conseguir, es que cuándo el Ping))) detecte un obstáculo a menos de 20cm el motor gire. Para ello me he visto obligado a cambiar el cableado respecto a cómo lo tenían en el tutorial, y el problema es que ahora dos de los motores no giran. He revisado que todos los cables estuvieran bien conectados, y lo mismo con los pins de Arduino, así que supongo que debe ser problema del código. He pensado que aquí quizás puedan ayudarme, así que les diré cómo he realizado las conexiones y también el código:

CONEXIONES:

Arduino se alimenta con una batería de 12V, conectados a VIM y GND.
Ping))) se alimenta a través de Arduino, 5V va conectado a 5V de Arduino, y GND a GND de Arduino. Sig. va al pin 12 de Arduino.
La placa de Motores se alimenta independientemente de Arduino, con una batería de 7,5 que va conectada a VMS i GND de delante. Los motores van conectados a VMS y GND de los lados.
Las conexiones entre Arduino y la placa de motores son:

Pin 2 a EB
Pin 3 a I3
Pin 4 a I4
Pin 7 a I2
Pin 8 a I1
Pin 9 a EA

CÓDIGO:

#define MOTOR1_CTL1  8  // I1  
#define MOTOR1_CTL2 7 // I2
#define MOTOR1_PWM   9 // EA  
#define MOTOR2_CTL1  4  // I3  
#define MOTOR2_CTL2  3  // I4  
#define MOTOR2_PWM   2 // EB  
#define MOTOR_DIR_FORWARD  0
#define MOTOR_DIR_BACKWARD   1
const int pingPin = 12;
  void setup()  

  {  
  Serial.begin(9600);
    // Setup pins for motor 1  

      pinMode(MOTOR1_CTL1,OUTPUT);

    pinMode(MOTOR1_CTL2,OUTPUT);

  pinMode(MOTOR1_PWM,OUTPUT); 

     

   // Setup pins for motor 2  

pinMode(MOTOR2_CTL1,OUTPUT);
pinMode(MOTOR2_CTL2,OUTPUT);
pinMode(MOTOR2_PWM,OUTPUT);
}



  void setSpeed(char motor_num, char motor_speed) 
  {  
     if (motor_num == 1)  
     {  
       analogWrite(MOTOR1_PWM, motor_speed);  
      }     

     else  
     {  
     analogWrite(MOTOR2_PWM, motor_speed);  
     }  
   }  
   void motorStart(char motor_num, byte direction)  //motor, Direcció
   {  
     char pin_ctl1;  
    char pin_ctl2;  
    if (motor_num == 1)  
     {  
        pin_ctl1 = MOTOR1_CTL1;  
     pin_ctl2 = MOTOR1_CTL2;  
      }     
      else  
      {  
         pin_ctl1 = MOTOR2_CTL1;  
         pin_ctl2 = MOTOR2_CTL2;       
     }  
      switch (direction)  
      {  
        case MOTOR_DIR_FORWARD:  
        {  
          digitalWrite(pin_ctl1,LOW);  
         digitalWrite(pin_ctl2,HIGH);           
       }  
        break;   
        case MOTOR_DIR_BACKWARD:  
        {  
           digitalWrite(pin_ctl1,HIGH);  
           digitalWrite(pin_ctl2,LOW);            
        }  
        break;           
      }  
   }  
   void motorStop(char motor_num)  
   {  
      setSpeed(motor_num, 0);  
      if (motor_num == 1)  
      {  
        digitalWrite(MOTOR1_CTL1,HIGH);  
        digitalWrite(MOTOR1_CTL2,HIGH);       
      }  
      else  
      {  
        digitalWrite(MOTOR2_CTL1,HIGH);  
        digitalWrite(MOTOR2_CTL2,HIGH);       
     
   
  }  
  
  
   }  
   void loop()  
   {  
     // Start motors!  
     
     motorStart(1, MOTOR_DIR_FORWARD);
     setSpeed(1, 200);
     motorStart(2, MOTOR_DIR_FORWARD);        
     setSpeed(2, 200);
     // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
    }

Espero que puedan ayudarme a resolver este problema. ¡Gracias! :slight_smile:

Hola! No revisé tu programación ni tu cableado. Pero leí lo siguiente:
"Ahora, lo que quiero conseguir, es que cuándo el Ping))) detecte un obstáculo a menos de 20cm el motor gire. Para ello me he visto obligado a cambiar el cableado respecto a cómo lo tenían en el tutorial"
Por qué cambiaste el cableado? Si podés controlar los motores, lo único que te va a faltar es añadirle el sensor ultrasónico a tu sistema y darle las ordenes al motor según la lectura...

la salida 2, no es una salida pwm. ya me dirás si este es el problema.

¡Saludos!

Me ví obligado a cambiar el cableado ya que sino no tenía suficiente potencia para alimentar al sensor y a los motores a la vez. Es por esto que decidí alimentar a Arduino y Ping))) independientemente de la placa de motores.

Voy a probar lo que me dice Nayma y ya os contaré si funciona o no.

¡Gracias a todos! :slight_smile:

¡Bieeen! ¡Ya funciooooonaaaa! :grin:

Nayma tenía razón, era problema del Pin en que había conectado el Ping))), así que sólo he tenido que cambiarlo de lugar y también su número en el código.
Además, he añadido un if y un else en el código para que gire cuándo detecte un obstáculo.

Os paso el código por si a alguien le puede servir:

#define MOTOR1_CTL1  8  // I1  
#define MOTOR1_CTL2 7 // I2
#define MOTOR1_PWM   9 // EA  
#define MOTOR2_CTL1  3  // I3  
#define MOTOR2_CTL2  4  // I4  
#define MOTOR2_PWM   5 // EB  
#define MOTOR_DIR_FORWARD  0
#define MOTOR_DIR_BACKWARD   1
const int pingPin = 12; //Pin PING)))
  void setup()  

  {  
  Serial.begin(9600);
    // Setup pins for motor 1  

      pinMode(MOTOR1_CTL1,OUTPUT);

    pinMode(MOTOR1_CTL2,OUTPUT);

  pinMode(MOTOR1_PWM,OUTPUT); 

     

   // Setup pins for motor 2  

pinMode(MOTOR2_CTL1,OUTPUT);
pinMode(MOTOR2_CTL2,OUTPUT);
pinMode(MOTOR2_PWM,OUTPUT);
}



  void setSpeed(char motor_num, char motor_speed) 
  {  
     if (motor_num == 1)  
     {  
       analogWrite(MOTOR1_PWM, motor_speed);  
      }     

     else  
     {  
     analogWrite(MOTOR2_PWM, motor_speed);  
     }  
   }  
   void motorStart(char motor_num, byte direction)  //motor, Direcció
   {  
     char pin_ctl1;  
    char pin_ctl2;  
    if (motor_num == 1)  
     {  
        pin_ctl1 = MOTOR1_CTL1;  
     pin_ctl2 = MOTOR1_CTL2;  
      }     
      else  
      {  
         pin_ctl1 = MOTOR2_CTL1;  
         pin_ctl2 = MOTOR2_CTL2;       
     }  
      switch (direction)  
      {  
        case MOTOR_DIR_FORWARD:  
        {  
          digitalWrite(pin_ctl1,LOW);  
         digitalWrite(pin_ctl2,HIGH);           
       }  
        break;   
        case MOTOR_DIR_BACKWARD:  
        {  
           digitalWrite(pin_ctl1,HIGH);  
           digitalWrite(pin_ctl2,LOW);            
        }  
        break;           
      }  
   }  
   void motorStop(char motor_num)  
   {  
      setSpeed(motor_num, 0);  
      if (motor_num == 1)  
      {  
        digitalWrite(MOTOR1_CTL1,HIGH);  
        digitalWrite(MOTOR1_CTL2,HIGH);       
      }  
      else  
      {  
        digitalWrite(MOTOR2_CTL1,HIGH);  
        digitalWrite(MOTOR2_CTL2,HIGH);       
     
   
  }  
  
  
   }  
   //////////////////////////////////////////////////////
   //              Bucli principal                     //
   //////////////////////////////////////////////////////
   
   
   
   void loop()  
   {  
     
     
     // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  pinMode(pingPin, OUTPUT);
  digitalWrite(pingPin, LOW);
  delayMicroseconds(2);
  digitalWrite(pingPin, HIGH);
  delayMicroseconds(5);
  digitalWrite(pingPin, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(pingPin, INPUT);
  duration = pulseIn(pingPin, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
  
  // Start motors!  
     if(cm < 30){
       motorStart(1, MOTOR_DIR_FORWARD);
       setSpeed(1, 200);
       motorStart(2, MOTOR_DIR_BACKWARD);        
     setSpeed(2, 200);
       Serial.println("Alerta!");
       motorStop(1);
       
     }
     else{
     motorStart(1, MOTOR_DIR_FORWARD);
     setSpeed(1, 100);
     motorStart(2, MOTOR_DIR_FORWARD);        
     setSpeed(2, 100);
     }
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
    }

¡Muchas gracias a todos! :slight_smile:

un placer....

espero nos compenses con unas fotos o video. :wink: :wink:

Ok! El robotejo no es gran cosa, pero en cuanto tenga un momento voy a colgar algun vídeo. :wink:

He estado dos semanas fuera y no he tenido ocasión de conectarme, pero lo prometido es deuda: un vídeo (sencillito) del funcionamiento de mi robotejo, bautizado "Marcelino".
¡Espero que os guste! :grin:

IKKARUS

ARDUINO2.avi (328 KB)

Hola soy Pablo, un nuevo miembro del foro. Me estoy basando en este código para construir un robot similar;

componentes:

Chasis 4wd, Arduino UNO (rev3), Ping Sensor HC-SR04 (4 pines), motor driver L298N.

conexiones:

Arduino--->Ping Sensor

pin 2 a Vcc
pin 3 a Trig
pin 4 a Echo
pin 5 a GND

Arduino ---> L298N

pin 8 a I1
pin 9 a I2
pin 11 a EA
pin 6 a I3
pin 7 a I4
pin 10 a EB

El codigo lo he adaptado ya que mi Ping Sensor es de 4 pines, pero algo debo estar haciendo mal ya que solo giran las 2 ruedas de la derecha y no responde a nada.

#define MOTOR1_CTL1  8  // I1  
#define MOTOR1_CTL2 9 // I2
#define MOTOR1_PWM   11 // EA  
#define MOTOR2_CTL1  6  // I3  
#define MOTOR2_CTL2  7  // I4  
#define MOTOR2_PWM   10 // EB  
#define MOTOR_DIR_FORWARD  0
#define MOTOR_DIR_BACKWARD   1

  void setup()  

  { 
   
   pinMode (2,OUTPUT); //pin 2 es VCC
   pinMode (5,OUTPUT); //pin 5 es GND
    
  Serial.begin(9600);
    // Setup pins for motor 1  

      pinMode(MOTOR1_CTL1,OUTPUT);

    pinMode(MOTOR1_CTL2,OUTPUT);

  pinMode(MOTOR1_PWM,OUTPUT); 

     

   // Setup pins for motor 2  

pinMode(MOTOR2_CTL1,OUTPUT);
pinMode(MOTOR2_CTL2,OUTPUT);
pinMode(MOTOR2_PWM,OUTPUT);
}



  void setSpeed(char motor_num, char motor_speed) 
  {  
     if (motor_num == 1)  
     {  
       analogWrite(MOTOR1_PWM, motor_speed);  
      }     

     else  
     {  
     analogWrite(MOTOR2_PWM, motor_speed);  
     }  
   }  
   void motorStart(char motor_num, byte direction)  //motor, Direcció
   {  
     char pin_ctl1;  
    char pin_ctl2;  
    if (motor_num == 1)  
     {  
        pin_ctl1 = MOTOR1_CTL1;  
     pin_ctl2 = MOTOR1_CTL2;  
      }     
      else  
      {  
         pin_ctl1 = MOTOR2_CTL1;  
         pin_ctl2 = MOTOR2_CTL2;       
     }  
      switch (direction)  
      {  
        case MOTOR_DIR_FORWARD:  
        {  
          digitalWrite(pin_ctl1,LOW);  
         digitalWrite(pin_ctl2,HIGH);           
       }  
        break;   
        case MOTOR_DIR_BACKWARD:  
        {  
           digitalWrite(pin_ctl1,HIGH);  
           digitalWrite(pin_ctl2,LOW);            
        }  
        break;           
      }  
   }  
   void motorStop(char motor_num)  
   {  
      setSpeed(motor_num, 0);  
      if (motor_num == 1)  
      {  
        digitalWrite(MOTOR1_CTL1,HIGH);  
        digitalWrite(MOTOR1_CTL2,HIGH);       
      }  
      else  
      {  
        digitalWrite(MOTOR2_CTL1,HIGH);  
        digitalWrite(MOTOR2_CTL2,HIGH);       
     
   
  }  
  
  
   }  
   //////////////////////////////////////////////////////
   //              Bucli principal                     //
   //////////////////////////////////////////////////////
   
   
   
   void loop()  
   {  
     
    digitalWrite(2, HIGH); 
     // establish variables for duration of the ping,
  // and the distance result in inches and centimeters:
  
  
  long duration, inches, cm;

  // The PING))) is triggered by a HIGH pulse of 2 or more microseconds.
  // Give a short LOW pulse beforehand to ensure a clean HIGH pulse:
  
  pinMode(3, OUTPUT);
  digitalWrite(3, LOW);
  delayMicroseconds(2);
  digitalWrite(3, HIGH);
  delayMicroseconds(5);
  digitalWrite(3, LOW);

  // The same pin is used to read the signal from the PING))): a HIGH
  // pulse whose duration is the time (in microseconds) from the sending
  // of the ping to the reception of its echo off of an object.
  pinMode(4, INPUT);
  duration = pulseIn(4, HIGH);

  // convert the time into a distance
  inches = microsecondsToInches(duration);
  cm = microsecondsToCentimeters(duration);
 
  Serial.print(inches);
  Serial.print("in, ");
  Serial.print(cm);
  Serial.print("cm");
  Serial.println();
 
  delay(100);
  
  // Start motors!  
     if(cm < 30){
       motorStart(1, MOTOR_DIR_FORWARD);
       setSpeed(1, 200);
       motorStart(2, MOTOR_DIR_BACKWARD);        
     setSpeed(2, 200);
       Serial.println("Alerta!");
       motorStop(1);
       
     }
     else{
     motorStart(1, MOTOR_DIR_FORWARD);
     setSpeed(1, 100);
     motorStart(2, MOTOR_DIR_FORWARD);        
     setSpeed(2, 100);
     }
}

long microsecondsToInches(long microseconds)
{
  // According to Parallax's datasheet for the PING))), there are
  // 73.746 microseconds per inch (i.e. sound travels at 1130 feet per
  // second).  This gives the distance travelled by the ping, outbound
  // and return, so we divide by 2 to get the distance of the obstacle.
  // See: http://www.parallax.com/dl/docs/prod/acc/28015-PING-v1.3.pdf
  return microseconds / 74 / 2;
}

long microsecondsToCentimeters(long microseconds)
{
  // The speed of sound is 340 m/s or 29 microseconds per centimeter.
  // The ping travels out and back, so to find the distance of the
  // object we take half of the distance travelled.
  return microseconds / 29 / 2;
    }

A ver si alguien me puede iluminar, muchas gracias :smiley:

Ya sé que debe ser una tontería, o una barbaridad en el código, pero es que no doy con ello... Agradecería una ayuda :grin: