# PID Controller to Turn: Couple questions on the code (pasted below)

I’ve written the following code. It’s a PID controller to have my robot turn 90 degrees left. I think I’m getting the hang of PID control. Couple questions I’ve got:

1. I need to set a cap for my integral term. What should I cap the integral at?
2. How can I use the integral term to correct steady state errors in this code? I don’t quite understand the function of the integral in this PID controller.
3. I understand the function of the derivative and proportion constants. I don’t quite understand how the integral term will correct steady state errors. Maybe there’s an issue with my code regarding how the integral of error is calculated.
4. I noticed that increasing kD (derivative constant) makes my robot oscillate more when getting closer to 90 degrees. Isn’t the derivative supposed to dampen oscillations?
``````  // PID Constants and Variables
double kP=2;
double kD=2;
double kI=1;
double error_prior=0;
double integral_prior=0;

turnSensorUpdate();
double angle=((int32_t)turnAngle >> 16) * 360 >> 16;
double error = 90-abs(angle);

double integral=integral_prior+error*(10);
double derivative = (error-error_prior)/10;
integral = constrain(integral,-90,90);

double turnSpeed=kP*error+kI*integral+kD*derivative;
motors.setSpeeds(-turnSpeed, turnSpeed);

error_prior - error;
integral_prior = integral;
delay(10);

``````

?

Error prior = the error detected on the last iteration of this PID controller.

Error = the error detected on the current iteration of the controller.

I think there was supposed to be an equal sign instead of a comma in between those.

You did not write the code, as claimed? That line is an obvious mistake. There may be others, as it is easy to get signs wrong, but I did not look past that one.

The Arduino PID library is well written and reliable.