Problem with If Statements in a Robot's Motor Feedback Control Routine

Rather than having the motors run on delay times, I would like them to run until the condition has been met and not increment to the next loop until that occurs. How do I accomplish this? Thanks.

What happens when it runs is that both motors try to run at the same time. The conditions work like a charm for each motor individually when the others are commented out.

if (Base < 370)
{
Base = analogRead(0); // read the input pin 0
Serial.println(" < 370 detected at base. Rotating clockwise ");
Serial.print("Base = ");
Serial.println(Base); // debug value
motor4.setSpeed(255);
motor4.run(FORWARD);
delay(500);
motor4.run(RELEASE);

}

else if (Base > 380) {
Base = analogRead(0); // read the input pin 0
Serial.println(" > 380 detected at base. Rotating counter-clockwise ");
Serial.print("Base = ");
Serial.println(Base); // debug value
motor4.setSpeed(255);
motor4.run(BACKWARD);
delay(500);
motor4.run(RELEASE);
}

if (Elbow < 545)
{
Serial.println(" < 545 detected at elbow. Rotating away from user ");
Elbow = analogRead(2); // read the input pin 2
Serial.print("Elbow = ");
Serial.println(Elbow); // debug value
motor3.setSpeed(255);
motor3.run(BACKWARD);
delay(500);
motor3.run(RELEASE);
}

else if (Elbow > 550) {
Serial.println(" > 550 detected at elbow. Rotating towards user ");
Elbow = analogRead(2); // read the input pin 2
Serial.print("Elbow = ");
Serial.println(Elbow); // debug value
motor3.setSpeed(255);
motor3.run(FORWARD);
delay(500);
motor3.run(RELEASE);
}

I tried WHILE and FOR but I couldn't get them to function, perhaps because I'm new to this.

This is the full code.

Start_Position_With_IfElse.ino (3.99 KB)

while (analogRead(0) < 370)
  {
    //commands to move the motor go here 
  }
//commands to stop motor go here

rszabo:
I would like them to run until the condition has been met and not increment to the next loop until that occurs. How do I accomplish this? Thanks.

What happens when it runs is that both motors try to run at the same time. The conditions work like a charm for each motor individually when the others are commented out.

It sounds as if you want to run several motors at the same time, monitor each of them and stop them when they reach the right position, and leave this block of code once all the motors have reached the right position. Is that the idea?

There are lots of different ways to do it. One fairly simple approach is to define a local variable for each motor which records whether that motor is moving. Keep looping until all motors are stopped.

baseMoving = true;
elbowMoving = true;
while(baseMoving || elbowMoving)
{
    if(basePosition < (baseTarget-10))
    {
        baseForward();
    }
    else if (basePosition > (baseTarget + 10))
    {
        baseBackward();
    }
    else
    {
        baseStop();
        baseMoving = false;
    }

    /// etc for elbow
}