Quote:
Originally Posted by Jared
|
I believe the mistake you made for the derivative calculation is that you never update the variable lastError in your update function. You also don't appear to initialize the variables i and lastError so if you try to run this code you'll get variable uninitialized errors, but I think you fixed this at competition and just didn't push that code to github else I don't see how this could work.
Code:
@Override
public void update() {
// PID calculations
double dt = .02; // length of time between each calculation
// calculate how far from our target we are
double error = setPoint - source.pidGet();
// p is proportional to error and our kP gain
double p = error;
// integrate error
i += error * dt;
// make sure it isn't too big
coerce(i, -max_I, max_I);
// differentiate error
double dError_dt = (error - lastError) / dt;
double d = dError_dt;
//output is sum of all terms multiplied by gains
double result = kP * p + kI * i + kD * d;
// check to see if we're at our target
if ((Math.abs(dError_dt) < max_derror_dt)
&& (Math.abs(error) < max_error)) {
// reset I if we want to
//possibly add decay?
i = (reset_I_whenOnTarget) ? 0 : i;
}
//set output
if(enabled){
output.pidWrite(result);
}
}