------------------------------------------pid.c----------------------------------------------------------------------------
#include "pid.h"
static pid_t gPid = {0};
void Pid_SetGain(float ProportionGain,float IntegralGain,float DerivativeGain)
{
gPid.ProportionGain = ProportionGain;
gPid.IntegralGain = IntegralGain;
gPid.DerivativeGain = DerivativeGain;
}
void Pid_SetPoint(float SetPoint)
{
gPid.SetPoint = SetPoint;
}
#ifdef INCREMENT_PID_CONTROL
void pid_compute(float CurValue) /* 增量型 */
{
float thisError = 0;
float increment = 0;
float pError,dError,iError;
thisError = gPid.SetPoint - CurValue; //得到偏差值
pError = thisError - gPid.LastError;
iError = thisError;
dError = thisError - 2 * (gPid.LastError) + gPid.Preerror;
increment = gPid.ProportionGain * pError + gPid.IntegralGain * iError + gPid.DerivativeGain * dError; //增量计算
gPid.Preerror = gPid.LastError; //存放偏差用于下次运算
gPid.LastError = thisError;
gPid.Result += increment;
}
#else
void pid_compute(float CurValue) /* 位置型 */
{
float thisError = 0;
thisError = Pid.SetPoint - CurValue;
gPid.Integral += thisError;
gPid.Result = Pid.ProportionGain * thisError \
+ Pid.IntegralGain * Pid.Integral \
+ Pid.DerivativeGain * (thisError - Pid.LastError);
gPid.LastError = thisError;
}
#endif
-----------------------------------------------------------------pid.h-------------------------------------------
#ifndef __PID_H__
#define __PID_H__
#define INCREMENT_PID_CONTROL
/*定义结构体和公用体*/
typedef struct
{
float SetPoint; //设定值
float ProportionGain; //比例系数
float IntegralGain; //积分系数
float DerivativeGain; //微分系数
float LastError; //前一拍偏差
float Result; //输出值
#ifdef INCREMENT_PID_CONTROL
float Integral; //积分值
float Preerror; //前两拍偏差
float DeadBand; //死区
#endif
}pid_t;
extern void Pid_SetGain(float ProportionGain,float IntegralGain,float DerivativeGain);
extern void Pid_SetPoint(float SetPoint);
extern void pid_compute(float CurValue);
#endif /* __PID_H__*/