Start motor for a defined time

Hi, I have this:

...code...

void backwards()
{
  digitalWrite(rightMotor1, HIGH);
}

...more code...

void loop ()
´{
   ...code...
      if (sensor = white)
          {
            backwards();
           }
  }

The robot goes forward and detects an obstacle, when it detects it, it identifies its color, if it is white, the robot goes backwards, but I need that backwards to run for a few seconds, how can I do that? Because if the sensor detects air it must go forward. Thanks, sorry for my english.

I need that backwards to run for a few seconds, how can I do that?

What do you want it to do after “a few seconds”?

void backwardsForAFewSecondsThenStop(unsigned long howLong)
{
  digitalWrite(rightMotor1, HIGH);
  delay(howLong);
  digitalWrite(rightMotor1, LOW);
}

I assume that the left motors are just along for the ride, along with rightMotor2.

Yes, actually, this is “void backwards()”

void atras()
 {
  Serial.print ("vamos adelante ");
  digitalWrite(motorPower, HIGH); 
  digitalWrite(rightMotor1, LOW);
  digitalWrite(rightMotor2, HIGH);
  analogWrite(rightMotorPWM, vel);
  digitalWrite(motorPower, HIGH);
  digitalWrite(leftMotor1, LOW);
  digitalWrite(leftMotor2, HIGH);
  analogWrite(leftMotorPWM, vel);

  return;
  }

I need to get to te beggining of the line and go to another located next to it :fearful:

Thanks!, I’ve got it!

And when the robot in on a delay, the motors will still be on? Thanks, I'm asking because I can't test it until tomorrow.

And when the robot in on a delay, the motors will still be on?

Yes.

void atras()
 {
  Serial.print ("vamos adelante ");
  digitalWrite(motorPower, HIGH); 
  digitalWrite(rightMotor1, LOW);
  digitalWrite(rightMotor2, HIGH);
  analogWrite(rightMotorPWM, vel);
  digitalWrite(motorPower, HIGH);
  digitalWrite(leftMotor1, LOW);
  digitalWrite(leftMotor2, HIGH);
  analogWrite(leftMotorPWM, vel);

  return;
  }

The return statement is not needed. When the end of the function is reached, it will return automatically.

There is not need to set the motorPower pin HIGH twice. The Arduino does remember that you set the pin to some state.

      if (sensor = white)

with a single equal sign is a common error in C. This probably should be (with two equal signs):

      if (sensor == white)

The first one sets sensor to the value white, and then the if statement determines whether sensor is non-zero. This could be what was intended, but not likely.

The second one is probably what was intended.

Hello again!
Thanks for answering me, I’ve got this:

//Código 27/4/2015 ;

#include <Servo.h>
#include <QTRSensors.h>
///////////////////////////////////
#define rightMotor1            6 // pin 1 de direccion del Motor Izquierdo
#define rightMotor2            5 // pin 2 de direccion del Motor Izquierdo
#define rightMotorPWM          9 // pin PWM del Motor Izquierdo9
#define leftMotor1            12 // pin 1 de direccion del Motor Derecho12
#define leftMotor2            11 // pin 2 de direccion del Motor Derecho11
#define leftMotorPWM           3 // pin PWM del Motor Derecho3
#define motorPower            10 // ??
#define NUM_SENSORS            4 // número de sensores usados
#define NUM_SAMPLES_PER_SENSOR 4 // cantidad de lecturas analogicas que serán leidas por sensor
#define EMITTER_PIN            2 // pin emisor del QTR
#define TIMEOUT             1000 // waits for 2500 us for sensor outputs to go low
#define LEDPIN                13 // número del pin de test
#define BUTTONPIN              2 // boton externo
///////////////////////////////////
QTRSensorsAnalog qtra((unsigned char[]) {1, 2, 3, 4}, NUM_SENSORS, NUM_SAMPLES_PER_SENSOR, EMITTER_PIN); //Orden de pines en los que están conectados A1, A2, A3, A4
unsigned int sensorValues[NUM_SENSORS];
int vel = 50; 
int CNY1 = A0;
int CNY2 = A5;
int val1 = 0;
int val2 = 0;
float med = 0;
int color = 0;
int negro = 950;
int blanco = 100;
int sinbote = 985;
Servo servoderecha;
Servo servoizquierda;

///////////////////////////////////

void setup()
{
  Serial.begin(9600);
  pinMode(CNY1, INPUT);  
  pinMode(CNY2, INPUT);  
  pinMode(LEDPIN          ,OUTPUT);
  pinMode(leftMotor1      ,OUTPUT);
  pinMode(leftMotor2      ,OUTPUT);
  pinMode(leftMotorPWM    ,OUTPUT);
  pinMode(rightMotor1     ,OUTPUT);
  pinMode(rightMotor2     ,OUTPUT);
  pinMode(rightMotorPWM   ,OUTPUT);
  pinMode(BUTTONPIN       ,INPUT);
  servoizquierda.attach(8);
  servoderecha.attach(7);
  while ( !digitalRead(BUTTONPIN) );
 // presiona boton para activar calibracion
  for ( int i=0; i<70; i++)      // Hace tomar la calibración unos segundos.
  {
    digitalWrite(LEDPIN, HIGH);  // Enciende el led que parpadea durante la calibración
    delay(20);
    qtra.calibrate();            // reads all sensors 10 times at 2.5 ms per six sensors (i.e. ~25 ms per call)
    digitalWrite(LEDPIN, LOW);   // Apaga led de calibración por cada ciclo
    delay(20);
  }

  digitalWrite(LEDPIN, LOW);     // Apaga el led para indicar que está finalizada la calibración

  // esperar 5 segundos 
  delay(2000);
  }

void abrepinza()
{
  Serial.print("Abriendo pinza");
  servoderecha.write(180);   //Calibrar para que lo suelte       
  servoizquierda.write(180); //Calibrar para que lo suelte
  delay(1000);
  return;
  }
void cierrapinza()
{
  Serial.print("Cerrando pinza");
  servoderecha.write(0);   //Calibrar para que lo coja       
  servoizquierda.write(0); //Calibrar para que lo coja
  delay (500);
  return;
  }
void adelante()
 {
  Serial.println ("Adelante");
  digitalWrite(motorPower, HIGH); 
  digitalWrite(rightMotor1, HIGH);
  digitalWrite(rightMotor2, LOW);
  analogWrite(rightMotorPWM, vel);
  digitalWrite(motorPower, HIGH);
  digitalWrite(leftMotor1, HIGH);
  digitalWrite(leftMotor2, LOW);
  analogWrite(leftMotorPWM, vel);
  return;
  }
void atras()
 {
  Serial.println ("Atrás");
  digitalWrite(motorPower, HIGH); 
  digitalWrite(rightMotor1, LOW);
  digitalWrite(rightMotor2, HIGH);
  analogWrite(rightMotorPWM, vel);
  digitalWrite(leftMotor1, LOW);
  digitalWrite(leftMotor2, HIGH);
  analogWrite(leftMotorPWM, vel);
  return;
  }
void parada()
  {
  Serial.println("Parada");
  digitalWrite(motorPower, LOW);
  return;
  }
void giraderecha() //Rueda izq adelante
  {
  Serial.println("giro derecha"); 
  digitalWrite(motorPower, HIGH);
  digitalWrite(rightMotor1, HIGH);
  digitalWrite(rightMotor2, LOW);
  analogWrite(rightMotorPWM, vel);
  digitalWrite(motorPower, HIGH);
  digitalWrite(leftMotor1, HIGH);
  digitalWrite(leftMotor2, LOW);
  analogWrite(leftMotorPWM,0);  
  return;
  } 
void giraizquierda()
  {
  Serial.println("giro izquierda");
  digitalWrite(motorPower, HIGH);
  digitalWrite(rightMotor1, LOW);
  digitalWrite(rightMotor2, HIGH);
  analogWrite(rightMotorPWM, 0);
  digitalWrite(motorPower, HIGH);
  digitalWrite(leftMotor1, HIGH);
  digitalWrite(leftMotor2, LOW);
  analogWrite(leftMotorPWM, vel);
  return;
  }
  ////////////////////////////////////////SLI
int siguelineas ()
{
 val1 = analogRead(CNY1); 
 val2 = analogRead(CNY2);
 med = (val1 + val2)/2;

if (med <= blanco)
{
   color = 1;
   return color;
}
else if (med >= negro && med < sinbote)
{
  color = 3;
  return color;
} 
else 
{
color == 2;

}
  Serial.println("Siguiendo linea...");
 delay(1000);
  
  unsigned int position = qtra.readLine(sensorValues);
    if (sensorValues[3] < 250 && sensorValues[2] > 750 && sensorValues[1] > 750 && sensorValues[0] < 250) 
  {
    adelante();
  }
    else if (sensorValues[3] < 250 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] < 250) 
  {
    parada();
    Serial.println("Siguelineas interrumpido: FUERA DE LINEA");
  }
    else if (sensorValues[3] < 250 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] > 750) 
  {
    giraderecha();
  } 
    else if (sensorValues[3] > 750 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] < 250) 
  {
    giraizquierda();
  }  
  return color;
 }
 ////////////////////////////////////////////////////////SLF
void loop()
{
 val1 = analogRead(CNY1); 
 val2 = analogRead(CNY2);
 med = (val1 + val2)/2;
if (med <= blanco)
{
color = 1; 
}
else if (med >= negro && med < sinbote)
{
color = 3;
} 
else 
{
color = 2;
}
Serial.print(color);
 unsigned int position = qtra.readLine(sensorValues);
if (sensorValues[3] < 750 && sensorValues[2] > 750 && sensorValues[1] > 750 && sensorValues[0] < 750) 
  {
    Serial.print("Estamos en inicio, empezamos ya...");
  }

  ///////////////////////AQUI EMPIEZA /////////////////////
  switch (color){
    case 1: {
      parada();
      adelante();
      delay(500); //Calibrar para que llegue al centro 
      parada();
      atras();
      delay(1500);  //Calibrar para que vuelva al principio de la línea
      parada();
      goto buscar_nueva_linea;
      break;
}  
    case 2: {
    siguelineas();
    break;
    }
    case 3: {
      parada();
      cierrapinza();
      delay(150);
        if (sensorValues[3] < 250 && sensorValues[2] > 750 && sensorValues[1] > 750 && sensorValues[0] < 250)
      {
        atras();
        }
      else if (sensorValues[3] < 250 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] < 250)
       {
       parada();
       buscar_nueva_linea:
       giraizquierda();
       delay(400); //Configurar para que gire 140 grados
       parada(); 
       abrepinza();
       while(sensorValues[3] < 250 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] < 250)
       {
       atras();
       }
       parada();
       atras();
       delay(500);
       while(sensorValues[3] < 250 && sensorValues[2] < 250 && sensorValues[1] < 250 && sensorValues[0] < 250)
       {
       atras();
       }
       parada();
       giraderecha(); //Para que coja la siguiente pista y pueda iniciar linea
       delay(100);
       parada();
       siguelineas();
       delay (800);
       parada();
       break;
       }    
   } //Cierre case 3
} //Cierre del switch
} //Cierre del loop

Is there something I must review?, I know “return;” is not needed, anything else?
Motors are not running, why, hardware problem?
When he is following the line, CNY70 sensors doesn’t change values and it follows line forever… How do I solve this? Robot is supposed to follow the line until “color” changes its value to 0 or 1, then the robot can move between lines.
Thanks!

Only one motor works with the code above. It seems that if I disable servos, all motors work perfectly, basically I quit this:

servoizquierda.attach(8);
servoderecha.attach(7);

And everything is fine, but I need those servos running! For the motor controller I'm using a "TB6612FNG dual motor driver carrier" Thanks!

To drive a servo, you need to send it pulses. The Servo library does that, using timer 1. That is the same timer needed to do PWM on pins 9 and 10. You need to use other pins for PWM, or a different servo library, like ServoTimer2.

Thanks!! :) I'm going to change library, and update here.