Pros Gyro Control Loop

I want to use a gyroscope for turning in auton but I’m having trouble with the control loop when it tries to turn past 360 it gets stuck jerking back and forth. Otherwise it works just fine but over complicated I’m sure.

int GyroPos() {
  return (int(gyro.get_value()) / 10);
}

void Rotate(double turn, int speed) {
int CurrectPos = (GyroPos() / 2);
turn = turn / 2;
bool Corrected = false;
bool IsOver = false;
turn = turn + CurrectPos;
if (turn > 180) {
  turn += -180;
  IsOver = true;
}
else if (turn < -180) {
  turn += 180;
  IsOver = true;
}
else {
  IsOver = false;
}

//Move IsOver Check to the outside of while
while (Corrected == false) {
  CurrectPos = (GyroPos() / 2);
  if (IsOver == false) {
    if (turn > CurrectPos) {
      FLMotor.move(speed);
      FRMotor.move(-speed);
      BLMotor.move(speed);
      BRMotor.move(-speed);
    }
    else if (turn < CurrectPos) {
      FLMotor.move(-speed);
      FRMotor.move(speed);
      BLMotor.move(-speed);
      BRMotor.move(speed);
    }
    else {
      FLMotor.move(0);
       FRMotor.move(0);
       BLMotor.move(0);
       BRMotor.move(0);
      Corrected = true;
    }
  }
  else {
    if (turn < CurrectPos) {
      FLMotor.move(speed);
      FRMotor.move(-speed);
      BLMotor.move(speed);
      BRMotor.move(-speed);
    }
    else if (turn > CurrectPos) {
      FLMotor.move(-speed);
      FRMotor.move(speed);
      BLMotor.move(-speed);
      BRMotor.move(speed);
    }
  else {
      FLMotor.move(0);
      FRMotor.move(0);
      BLMotor.move(0);
      BRMotor.move(0);
      Corrected = true;
  }
}
}
}

I figured it out for any one that is looking for working code this is what I came up with.

int GyroPos() {
return (int(gyro.get_value()) / 10);
}


//Turns the robot to the target position
void Rotate(int TargetPos, int speed) {
bool IsLeft;
if (TargetPos > 0) {
    FLMotor.move(speed);
    FRMotor.move(-speed);
    BLMotor.move(speed);
    BRMotor.move(-speed);
    IsLeft = true;
}
else {
    FLMotor.move(-speed);
    FRMotor.move(speed);
    BLMotor.move(-speed);
    BRMotor.move(speed);
    IsLeft = false;
}

TargetPos = TargetPos / 2;
TargetPos = TargetPos + (GyroPos() / 2);

if (TargetPos > 180) {
    TargetPos = TargetPos - 180;
}
if (TargetPos < -180) {
    TargetPos = TargetPos + 180;
}


if (IsLeft == true) {
    while (TargetPos >= (GyroPos() / 2)) {
    pros::delay(20);
    }
    FLMotor.move(0);
    FRMotor.move(0);
    BLMotor.move(0);
    BRMotor.move(0);
}
else {
    while (TargetPos <= (GyroPos() / 2)) {
    pros::delay(20);
    }
    FLMotor.move(0);
    FRMotor.move(0);
    BLMotor.move(0);
    BRMotor.move(0);
}
}
1 Like