Inertial turning the wrong way

When telling my robot to turn to a negative number with my inertial sensor PID code it will turn the incorrect way and take a longer time to reach the set target, also leading to inaccurate results due to the extra speed. Any help would be greatly appreciated.

void turn(int speed){
  int moveguy = speed*0.5;
  if(runTurn == true){
  TopLeft = moveguy;
  BottomLeft = moveguy;
  TopRight = -moveguy;
  BottomRight = -moveguy;

void PIDTurn(void* Param){
	while(1==1) {

     gyroPOS = ((inertial.get_rotation()+inertial2.get_rotation())/2);

		Gerror = turnTarget - inertial.get_rotation();

		Gproportion = gyroKp * Gerror;

    if (Gproportion > maxTurnPower) Gproportion = maxTurnPower;
    else if (Gproportion < -maxTurnPower) Gproportion = -maxTurnPower;

		Gderivative = gyroKd * (Gerror - GprevError);
		GprevError = Gerror;

    Gintegral = gyroKi * (Gintegral + Gerror);

		Graw = Gproportion + Gderivative + Gintegral;


		newTurnTarget = false;


void setTurn(int degrees){
  runPID = false;
  runTurn = true;
  if(degrees>=0) turnTarget = degrees;
  else if(degrees<0) turnTarget = degrees+360;

//  turnTarget = degrees;
  newTurnTarget = true;

When you input a negative number, you set the target equal to 360+input, making the robot think it should turn towards a positive target, which is why it turns the wrong way. You should add something in your code that makes the speed negative if the input is negative or if the current position is more than 180 degrees away from the target.

1 Like

OH yea i had that problem too. You should add something along the lines of what ashatoolisidas said.

Something like:

If (gyroDif > 180){
gyroDif -= 360;
if (gyroDif<-180){