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