#ifndef PID_H
#define PID_H
#define Target_dist (100000)
#define max (256*4)
#define MAX_LIMIT 9999999
#define MIN_LIMIT -9999999
typedef struct PID_PAR
{
long Ref;
long Fdb;
long Err;
long Kp;
long Up;
long Ui;
long Ud;
long OutPreSat;
long IntegralMax;
long IntegralMin;
long IntegralErr;
long OutMax;
long OutMin;
long Out;
long SatErr;
long Ki;
long Kc;
long Kd;
long Up1;
long Dt;
void (*calc)();
} PID_PAR;
void PID_Init(void);
void PID_Control(PID_PAR *pid);
extern struct PID_PAR pid_par;
#endif
#include "PID.h"
void PID_Init(void)
{
pid_par.Ref = Target_dist;
pid_par.Fdb = 0;
pid_par.Err = 0;
pid_par.Kp = 1;
pid_par.Up = 0;
pid_par.Ui = 0;
pid_par.Ud = 0;
pid_par.OutPreSat = 0;
pid_par.IntegralMax = MAX_LIMIT;
pid_par.IntegralMin = MIN_LIMIT;
pid_par.IntegralErr = 0;
pid_par.OutMax = MAX_LIMIT;
pid_par.OutMin = MIN_LIMIT;
pid_par.Out = 0;
pid_par.SatErr = 0;
pid_par.Ki = 1;
pid_par.Kc = 1;
pid_par.Kd = 1;
pid_par.Up1 = 0;
pid_par.Dt = 1;
pid_par.calc = (&PID_Control);
}
void PID_Control(PID_PAR *pid)
{
long cal_result;
long present_err;
present_err = pid->Ref - pid->Fdb;
cal_result = pid->Ki * present_err;
if (cal_result > pid->IntegralMax)
{
cal_result = pid->IntegralMax;
}
else if (cal_result < pid->IntegralMin)
{
cal_result = pid->IntegralMin;
}
cal_result += pid->Kp * present_err;
pid->Ui += present_err * pid->Dt;
pid->Ud = (present_err - pid->Up1) / (pid->Dt);
cal_result += pid->Kd * pid->Ud;
pid->Up1 = present_err;
if (cal_result > pid->OutMax)
{
pid->Out = pid->OutMax;
pid->Err = -1;
}
else if (cal_result < pid->OutMin)
{
pid->Out = pid->OutMin;
pid->Err = -1;
}
else
{
pid->Out = cal_result;
pid->Err = 0;
}
}
#define TARGET SPEED 100
struct PID_PAR pid_par;
void main()
{
fPID_Init();
pid_par.Ref = TARGET_SPEED;
While(1)
{
get_peed(&Feedback);
pid_par.Fdb = Feedback;
pid_par.calc(&pid_par);
Cal_Result = pid_par.Out;
set speed(Cal Result);
}
}