Another interesting variation on the PID algorithms previously posted is a slight twist on the Derivative term. It uses the position instead of the error in the D term calculation. This seems to work slightly better in practice, although each system is unique.
double UpdatePID(SPid * pid, double error, double position)
pTerm = pid->pGain * error;
// calculate the proportional term
// calculate the integral state with appropriate limiting
pid->iState += error;
if (pid->iState > pid->iMax) pid->iState = pid->iMax;
else if (pid->iState < pid->iMin) pid->iState = pid->iMin;
iTerm = pid->iGain * iState; // calculate the integral term
dTerm = pid->dGain * (position - pid->dState);
pid->dState = position;
return pTerm + iTerm - dTerm;
This code is taken from PID Without a PhD
. The author explains his reasoning behind the difference from more traditional PID algorithms. This is the approach that I took with the BCS-460 control loops. I believe that the PID code in the Aurdino Playground takes a similar approach.