Motor Driver(MDS40A) and MaxBotix(LV EZ-1) Sensor

I am currently doing my final year project about WheelChair.

void setup()
{
  Serial.begin(9600);
  Serial2.begin(9600);    /*----(Right Motor Serial Comm)----*/
  Serial3.begin(9600);   /*----(Left Motor Serial Comm)----*/
  Serial.flush(); // Waits for the transmission of outgoing serial data to complete
  Gsm_Init();
  Motor_Joy_Init();
  Sensor_Init();
  Bat_Init();
  Buzzer_Init();
  delay(250);
}

void loop()
{
  Sensor();
  //if(cm > 70)
  //{
    //Sensor();
    //Motor();
  //}
  Motor();
  Battery_Indicator();
  Buzzer();

  GsmState = digitalRead(GsmButton);
  
  if (GsmState == HIGH)
  {
    Gsm();
  }
  delay(50);
}

void Sensor()
{
  Front1 = pulseIn(Sensor1, HIGH); //reads the maxsonar sensor and divides the value by 2
  inches = Front1/147;
  cm = inches * 2.54;               //Convert to Cm
  // approximate distance in cm
  Serial.print(cm); // prints the sensor information from the maxsonar to the serial monitor 
  Serial.println(" cm Front1");

  if (cm < 70) 
  { // if something is 70 cm away 
    Serial2.write(127);
    Serial3.write(127);
  }
}

void Motor()
{
  Start:
  digitalWrite(mtr1_In2, HIGH);
  digitalWrite(mtr2_In2, HIGH); // The Slave Select (IN2) for MDS40A set HIGH
  
    
  Xvalue = analogRead (X_AXIS); /*----(Read the X value and display it)----*/
  Serial.print("X:");
  Serial.print(Xvalue, DEC );
    
  Yvalue = analogRead (Y_AXIS);/*----(Read the Y value and display it)----*/
  Serial.print ( " | Y:" );
  Serial.print(Yvalue, DEC );
    
  Serial.println (); 
  delay(250);
  
  
  //Foward
  if((Xvalue >= 0 && Yvalue >= 513) &&  (Xvalue <=450 && Yvalue <=516)) // Check whether Up button pressed
  { // both motors rotate clockwise (CCW)
    Serial2.write(255);
    Serial3.write(255);
    Serial.println("Foward");
    delay(250);
    
    while(cm < 70)
    {
      Serial2.write(127);
      Serial3.write(127);
      delay(2000);
      goto Start;
    }
    
  }
}

Here is a part of my code. The problem is that, I want the motor to stop when there is an obstacle in front of the sensor and will be able to move once there is no obstacle. Once the program enters the while loop(in the motor function) it will stop there forever. I have also tried replacing the while loop with an if condition, but that also didn't work.

Any help would be appreciated :sweat_smile: :sweat_smile:

up

Once you enter the while loop, you never touch cm again so if it's less than 70 at that point, your code will never exit the motor function.

wildbill:
Once you enter the while loop, you never touch cm again so if it's less than 70 at that point, your code will never exit the motor function.

The way to correct that, of course, is to read the sensor again, in the while loop.