typedef struct{
volatile int SetPoint;
volatile double Proportion;
volatile double Integral;
volatile double Derivative;
volatile int LastError;
volatile int PrevError;
}PID;
宏定義
#define P_DATA 3.2
#define I_DATA 1.1
#define D_DATA -0.15
SetPoint設(shè)置目標(biāo)參數(shù)康辑,若是控制電機(jī)摄欲,就是目標(biāo)速度。Proportion疮薇、Integral胸墙、Derivative分別是P、I按咒、D參數(shù)迟隅。LastError上一次的偏差值。PrevError上上次的偏差值。
void IncPIDInit(void)
{
sptr->LastError = 0;
sptr->PrevError = 0;
sptr->Proportion = P_DATA;
sptr->Integral = I_DATA;
sptr->Derivative = D_DATA;
sptr->SetPoint = 100;
}
int IncPIDCalc(int NextPoint)
{
int iError;
int iIncpid;
iError = sptr->SetPoint - NextPoint;
ilncpid = (sptr->Proportion*iError)
-(sptr->Integral*sptr->LastError)
+(sptr->Derivative*sptr->PrevError);
sptr->PrevError = sptr->LastError;
sptr->LastError = iError;
return (ilncpid);
}
count = 當(dāng)前值;
para = lncPIDCalc(count);
if((para<-3)||(para>3)) //避免誤差較小的時(shí)候引起震蕩
PWM_Duty += para;
if(PWM_Duty>899)
PWM_Duty = 899;