Main Page | Data Structures | File List | Data Fields | Globals | Related Pages

pid.c

Go to the documentation of this file.
00001 // This file has been prepared for Doxygen automatic documentation generation.
00022 #include "pid.h"
00023 
00033 void Init_PID(int p_factor, int i_factor, int d_factor, struct PID_DATA *pid)
00034 // Set up PID controller parameters
00035 {
00036   // Start values for PID controller
00037   pid->SUM_ERROR = 0;
00038   pid->LAST_PROCESS_VALUE = 0;
00039   // Tuning constants for PID loop
00040   pid->P_FACTOR = p_factor;
00041   pid->I_FACTOR = i_factor;
00042   pid->D_FACTOR = d_factor;
00043   // Limits to avoid overflow
00044   pid->MAX_ERROR = MAX_INT / (pid->P_FACTOR + 1);
00045   pid->MAX_SUM_ERROR = MAX_INT / (pid->I_FACTOR + 1);
00046 }
00047 
00048 
00057 int PID(int setPoint, int processValue, struct PID_DATA *pid_st)
00058 {
00059   int error, p_term, i_term, d_term;
00060   long ret, temp;
00061 
00062   error = setPoint - processValue;
00063 
00064   // Calculate Pterm and limit error overflow
00065   if(error > pid_st->MAX_ERROR)
00066     p_term = MAX_INT;
00067   else if(error < -pid_st->MAX_ERROR)
00068     p_term = -MAX_INT;
00069   else
00070     p_term = pid_st->P_FACTOR * error;
00071 
00072   // Calculate Iterm and limit integral runaway
00073   temp = (long)pid_st->SUM_ERROR + error;
00074   if(temp > pid_st->MAX_SUM_ERROR){
00075     i_term = MAX_INT;
00076     pid_st->SUM_ERROR = pid_st->MAX_SUM_ERROR;
00077   }
00078   else if(temp < -pid_st->MAX_SUM_ERROR){
00079     i_term = -MAX_INT;
00080     pid_st->SUM_ERROR = -pid_st->MAX_SUM_ERROR;
00081   }
00082   else
00083     pid_st->SUM_ERROR = temp;
00084     i_term = pid_st->I_FACTOR * pid_st->SUM_ERROR;
00085 
00086   // Calculate Dterm
00087   d_term = pid_st->D_FACTOR * (pid_st->LAST_PROCESS_VALUE - processValue);
00088 
00089   pid_st->LAST_PROCESS_VALUE = processValue;
00090 
00091   //ret = (((long)p_term + i_term + d_term))/128;
00092   ret = (((long)p_term + i_term + d_term)) >> 7; // <--- scale back down (right shift seven bits = divide by 128)
00093   if(ret > MAX_INT)
00094     ret = MAX_INT;
00095   else if(ret < -MAX_INT)
00096     ret = -MAX_INT;
00097   return((int)ret);
00098 }
00099 

Generated on Thu Nov 10 11:12:11 2005 for AVR221 - PID controller by  doxygen 1.4.4