IR Sensor and if statement problems

Hi all

I’m basically trying to spin a motor when something crosses an IR sensor line. When the first motor reaches the line, it should stop and tell the second motor to spin and reach the IR line and stop, to catch up.

I’ve got a few if statements together so when one becomes true, it’ll start another one. When something goes between min1 and max 1, it works fine. However it doesn’t seem to test the second if statement. Any reason why?

Code:

#include <AFMotor.h>
AF_DCMotor motor1(1);
AF_DCMotor motor2(2);

const int min1 = 50;
const int max1 = 150;

const int min2 = 150;
const int max2 = 200;

int sensorValue = 0; 

void setup(){

  // turn motors on
  motor1.setSpeed(255);
  motor1.run(RELEASE);
  motor2.setSpeed(255);
  motor2.run(RELEASE);

}

void loop(){
  int val = analogRead(sensorValue);

  motor1.run(FORWARD); // run the motor forward

  if (val > min1 && val < max1) {

    motor1.run(RELEASE); // stop motor 1
    motor2.run(FORWARD); // run the 2nd motor forward

    if (val > min2 && val < max2) {

      motor2.run(RELEASE); // stop motor 2

    }
  }
}

Thanks

There’s nothing inside the condition to change “Val”

Thanks AWOL

What would I need to change or update val?

Another analogRead, but it isn't quite that simple, because the value is unlikely to have changed much in the 120 or so microseconds since you last read it.

You may need a while loop.

cool.

or a small delay?

On testing, the delay does't work and yes, the value changes by about 2.. not very much.

I'm quite new to Arduino, could you give me some pointers as to how I would change my code to add a while loop?

I'm quite new to Arduino, could you give me some pointers as to how I would change my code to add a while loop?

Change if to while.