pid_control.c
Go to the documentation of this file.00001 00040 #include "pid_control.h" 00041 00042 #include <cfg/debug.h> 00043 00047 piddata_t pid_control_update(PidContext *pid_ctx, piddata_t target, piddata_t curr_pos) 00048 { 00049 piddata_t P; 00050 piddata_t I; 00051 piddata_t D; 00052 piddata_t err; 00053 00054 //Compute current error. 00055 err = target - curr_pos; 00056 00057 /* 00058 * Compute Proportional contribute 00059 */ 00060 P = err * pid_ctx->cfg->kp; 00061 00062 //Update integral state error 00063 pid_ctx->i_state += err; 00064 00065 //Clamp integral state between i_min and i_max 00066 pid_ctx->i_state = MINMAX(pid_ctx->cfg->i_min, pid_ctx->i_state, pid_ctx->cfg->i_max); 00067 00068 /* 00069 * Compute Integral contribute 00070 * 00071 * note: for computing the integral contribute we use a sample period in seconds 00072 * and so we divide sample_period in microsenconds for 1000. 00073 */ 00074 I = pid_ctx->i_state * pid_ctx->cfg->ki * ((piddata_t)pid_ctx->cfg->sample_period / 1000); 00075 00076 00077 /* 00078 * Compute derivative contribute 00079 */ 00080 D = (err - pid_ctx->prev_err) * pid_ctx->cfg->kd / ((piddata_t)pid_ctx->cfg->sample_period / 1000); 00081 00082 00083 // TRACEMSG("curr_pos[%lf],tgt[%lf],err[%f],P[%f],I[%f],D[%f]", curr_pos, target, err, P, I, D); 00084 00085 00086 //Store the last error value 00087 pid_ctx->prev_err = err; 00088 piddata_t pid = MINMAX(pid_ctx->cfg->out_min, (P + I + D), pid_ctx->cfg->out_max); 00089 00090 // TRACEMSG("pid[%lf]",pid); 00091 00092 //Clamp out between out_min and out_max 00093 return pid; 00094 } 00095 00099 void pid_control_init(PidContext *pid_ctx, const PidCfg *pid_cfg) 00100 { 00101 /* 00102 * Init all values of pid control struct 00103 */ 00104 pid_ctx->cfg = pid_cfg; 00105 00106 pid_control_reset(pid_ctx); 00107 00108 } 00109
