how do i stop my robot motors from being stuck in a loop

Viewed 31

I am using photoresistors to get a reading of "light" and i am wanting to move left and right depending what sensor has a stronger reading. And I also want it to just move straight if the difference of the two reading from the photoresistor hits a value.

At the moment it will get stuck in a if statement and will not change the direction of the motors.

Code:

#include <RedBot.h>
#include <Servo.h>

RedBotMotors motors;
const int LightPin_1 = A2;
const int LightPin_2 = A3;


void setup() {
  Serial.begin(9600);
  pinMode(LightPin_1, INPUT);
  pinMode(LightPin_2, INPUT);
  

}

void loop() {
int Light_Status_1 = analogRead(LightPin_1);
int Light_Status_2 = analogRead(LightPin_2);

 
// motors.drive(200);
  Light_Scan();

}

void Light_Scan(){
int Light_Status_1 = analogRead(LightPin_1);
int Light_Status_2 = analogRead(LightPin_2);
const int Range = 130;
int Difference = Light_Status_1 - Light_Status_2;


delay(2000);
 if (Light_Status_1 < Light_Status_2 && Difference >= Light_Status_1 )
 {
  Serial.println("Light 1:");
  Serial.println(Light_Status_1);
  Serial.println("Difference:");
  Serial.println(Difference);

  Serial.println("---------------------------------------");
  
 } else if (Light_Status_1 > Light_Status_2 ){
  Serial.println("Light 2:");
  Serial.println(Light_Status_2);
  Serial.println("Difference:");
  Serial.println(Difference);

   Serial.println("---------------------------------------");
 
} else if (Difference <= Light_Status_1){
 motors.drive(100); 
  delay(2000);
  Serial.print(Difference);
  Serial.println("stright");
  Serial.println("---------------------------------------");
} else {
 motors.drive(100); 
  delay(2000);
  Serial.print(Difference);
  Serial.println("stright1");
  Serial.println("---------------------------------------");
}
  
}
1 Answers

The first condition Light_Status_1 < Light_Status_2 && Difference >= Light_Status_1 is never satisfied: Difference = Light_Status_1 - Light_Status_2, so Light_Status_1 - Light_Status_2 >= Light_Status_1, that is -Light_Status_2 >= 0 but Light_Status_2 >= 0.

The second condition Light_Status_1 > Light_Status_2 is a legit check.

The third condition is satisfied every time: Difference <= Light_Status_1, that is Light_Status_1 - Light_Status_2 <= Light_Status_1, that is -Light_Status_2 <= 0 which is true because Light_Status_2 >= 0.

Related