unsigned int PID_Calculate(float SetPoint, float InputValue, char flag)
{
float Err_Curr, Derivate_Term, Proportional_Term, Integral_Term, Result;
static float Err_Prev, Acum_Integral_Err;
Err_Curr = SetPoint - InputValue;// Error is calculated by calculating difference of Set_point and measured value.
if (PID_First_Time ==1) // Since the controller is running for the first time there will be no accumilative errors
{
PID_First_Time = 0;
Err_Prev = 0.0;
Acum_Integral_Err = 0.0;
}
// Proportional term is calculated by multiplying current error by Kp easy peasy!!
Proportional_Term = Err_Curr * PID_Kp;
// This term is about calculating rate of change of error over time(PID loop cycle times) multiplied by Kd.
Derivate_Term = ((Err_Curr - Err_Prev)/ PID_CYCLE_TIME)*PID_Kd;
// Integral Term is calculated below
Acum_Integral_Err = Acum_Integral_Err + (((Err_Curr + Err_Prev)/2) * PID_CYCLE_TIME);
if (Err_Curr <= 0)
{
Acum_Integral_Err *= 0.90;//scale down the integral term to reduce over shoot see this in Bruce Land video around 40 minute
}
Integral_Term = PID_Ki * Acum_Integral_Err ;
// This is integral windup
if (Integral_Term < -200.00) // Integral term limited to 20% of full sale value
Integral_Term = -200.00;
if (Integral_Term > 200.00)
Integral_Term = 200.00; // Integral term limited to 20% of full sale value
Result = Proportional_Term + Integral_Term + Derivate_Term; //Adding P + I + D terms
if (Result > 1000.00) // Result bound to max upper limit of the PWM
{
Result = 1000.00;
}