I need help in regards to this while loop. It uses an inertial sensor to correct itself on turns, but after I want it to end (2 seconds) the while loop doesn't stop. How can I get it to stop

 TurnAuton = true;

    while (TurnAuton == true) {
      targetHeading = 180;   
      actualHeading = Inertial3.heading(degrees);
      error = targetHeading - actualHeading;
      motorSpeed = 0.5*abs(error);
      Drivetrain.setTurnVelocity(motorSpeed, pct);
      Drivetrain.turn(left);
    }

    wait(2, seconds); 

    TurnAuton = false;
    Drivetrain.stop();

The while loop is while (TurnAuton == true), which means that it will continue running when TurnAuton is true. But nothing in the while loop itself changes TurnAuton to false; therefore, the loop will run forever.

To stop the loop, you have to find a threshold of error (suggestion: 0.5 to 2 degrees). If your error is less than your threshold, then set TurnAuton to false. That will then exit out of your while loop.

1 Like

I have found a solution, Zayn had pointed in the right direction and had corrected my view on “while loops” and I would like to thank you for that. What I did was set up a different auton task that would set TurnAuton = false after my desired amount of time that it would run. This would however cause the robot to spin forever but it is not something a Drivetrain.stop(); couldn’t fix. If you want the code just tell me.

1 Like