# Inertial Sensor PID Too Much Variation

I’m trying to create a PID for my robot’s rotation using Vexcode, but whenever I try to run multiple 90 degree turns, some of the turns are way off while others are perfectly fine.

``````double kPAngle = 0.1;
double kIAngle = 0.0;
double kDAngle = 0.0;
double maxSpeed = 6;

void rotatePID(double angleTurn) {
double error = 0;
double prevError = 0;
double derivative = 0;
double integral = 0;

while( fabs(iSensor.rotation() - angleTurn) > 0.5) {
error = angleTurn - iSensor.rotation(rotationUnits::deg);
derivative = error - prevError;
prevError = error;

if(fabs(error) < 5 && error != 0) {
integral += error;
}
else {
integral = 0;
}

double powerDrive = error*kPAngle + derivative*kDAngle + integral*kIAngle;

if(powerDrive > maxSpeed) {
powerDrive = maxSpeed;
}
else if(powerDrive < -maxSpeed) {
powerDrive = -maxSpeed;
}

cout << "power: " << powerDrive << endl;
cout << "angle: " << iSensor.rotation() << endl;
cout << "error: " << error << endl;
// cout << "prevError: " << prevError << endl;
// cout << "derivative: " << derivative << endl;
// cout << "integral: " << integral*kIDrive << endl;
cout << "////" << endl;

// turning = true;
// goalVoltage = powerDrive;
rightDt.spin(rightSide, powerDrive, voltageUnits::volt);
leftDt.spin(leftSide, powerDrive, voltageUnits::volt);

}

// turning = false;
// goalVoltage = 0;
dt.stop(brake);
}``````
``````  iSensor.calibrate(2000);
cout << "Done calibrating" << endl;

iSensor.setRotation(270.00, rotationUnits::deg);
cout << "Rotation: " << iSensor.rotation() << endl;

rotatePID(180);