Robot moving too much or too litte

We use an AutonTurnAutonomous function during autonomous to turn. But when we enter the values for how much we want to turn, it doesn’t do what we want it to. For example, I said for it to turn 90 degrees but it turned 20 and self corrected itself back to the original starting position. Then I tried 360 and it kept on spinning for more than 15 secs. What could be the problem?

// Used to turn the robot in autonomous
void autonTurnAutonomous(int degrees, bool isRight)
{
  // resets the value of the inertia sensor
  inertia.resetRotation();

  // while the intertia sensor is not equal to the number of degrees desired
  while (inertia.value() < degrees)
  {

    // If turning right
    if (isRight)
    {
      DriveL.spin(forward, 20, percent);
      DriveR.spin(reverse, 20, percent);
    }
    else if (!isRight)
    {
      DriveL.spin(reverse, 20, percent);
      DriveR.spin(forward, 20, percent);
    }

    wait (20, msec);
  }

  while (inertia.value() == degrees)
  {

    DriveL.setStopping(hold);
    DriveR.setStopping(hold);
  }
   while (inertia.value() > degrees)
    {

    // If turning right
    if (isRight)
    {
      DriveL.spin(reverse, 10, percent);
      DriveR.spin(forward, 10, percent);
    }
    else if (!isRight)
    {
      DriveL.spin(forward, 10, percent);
      DriveR.spin(reverse, 10, percent);
    }
    }



  // stops the motors
  DriveL.stop();
  DriveR.stop();

  wait (20, msec);
}

The problem is with how you are controlling the robot. While you do reduce speed once it has overshot the target, the speed is not modified in response to how far away you are from the target. This can be solved by using a PID system which stands for proportional, integral, derivative. For a simple P controller the speed is varied proportionally to how far away you are from the target. This is called error. The effect of this is that the closer you get to your target, the slower you get. The integral term is based off of the sum of error and helps reduce steady-state error. Finally, the derivative term is based off of the rate of change in error and helps make sure you slow down if error is changing too fast. Here’s a document by George Gillard that goes into how PID controllers work.
introduction_to_pid_controllers_ed2.pdf (400.2 KB)