pid_control.c

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