pid.c

Go to the documentation of this file.
00001 /* This file has been prepared for Doxygen automatic documentation generation.*/
00028 #include "pid.h"
00029 #include "stdint.h"
00030 
00040 void pid_Init(int16_t p_factor, int16_t i_factor, int16_t d_factor, struct PID_DATA *pid)
00041 // Set up PID controller parameters
00042 {
00043   // Start values for PID controller
00044   pid->sumError = 0;
00045   pid->lastProcessValue = 0;
00046   // Tuning constants for PID loop
00047   pid->P_Factor = p_factor;
00048   pid->I_Factor = i_factor;
00049   pid->D_Factor = d_factor;
00050   // Limits to avoid overflow
00051   pid->maxError = MAX_INT / (pid->P_Factor + 1);
00052   pid->maxSumError = MAX_I_TERM / (pid->I_Factor + 1);
00053 }
00054 
00055 
00064 int16_t pid_Controller(int16_t setPoint, int16_t processValue, struct PID_DATA *pid_st)
00065 {
00066   int16_t error, p_term, d_term;
00067   int32_t i_term, ret, temp;
00068 
00069   error = setPoint - processValue;
00070 
00071   // Calculate Pterm and limit error overflow
00072   if (error > pid_st->maxError){
00073     p_term = MAX_INT;
00074   }
00075   else if (error < -pid_st->maxError){
00076     p_term = -MAX_INT;
00077   }
00078   else{
00079     p_term = pid_st->P_Factor * error;
00080   }
00081 
00082   // Calculate Iterm and limit integral runaway
00083   temp = pid_st->sumError + error;
00084   if(temp > pid_st->maxSumError){
00085     i_term = MAX_I_TERM;
00086     pid_st->sumError = pid_st->maxSumError;
00087   }
00088   else if(temp < -pid_st->maxSumError){
00089     i_term = -MAX_I_TERM;
00090     pid_st->sumError = -pid_st->maxSumError;
00091   }
00092   else{
00093     pid_st->sumError = temp;
00094     i_term = pid_st->I_Factor * pid_st->sumError;
00095   }
00096 
00097   // Calculate Dterm
00098   d_term = pid_st->D_Factor * (pid_st->lastProcessValue - processValue);
00099 
00100   pid_st->lastProcessValue = processValue;
00101 
00102   ret = (p_term + i_term + d_term) / SCALING_FACTOR;
00103   if(ret > MAX_INT){
00104     ret = MAX_INT;
00105   }
00106   else if(ret < -MAX_INT){
00107     ret = -MAX_INT;
00108   }
00109 
00110   return((int16_t)ret);
00111 }
00112 
00117 void pid_Reset_Integrator(pidData_t *pid_st)
00118 {
00119   pid_st->sumError = 0;
00120 }

Generated on Wed Oct 10 15:31:43 2007 for AVR449 by  doxygen 1.5.2