前文对PID算法离散化和增量式PID算法原理进行来探索,之后又使用Matlab进行了仿真实验,对PID三个参数又有了更深入的认识,接下来我们来使用C语言进行PID算法实现,并且结合控制电机的项目来深入学习。
1、PID 算法C 语言原代码
先贴上一种常见的比较通用的C语言增量式PID算法吧
typedef struct PID
{
intSetPoint; //设定目标 DesiredValue
longSumError; //误差累计
doubleProportion; //比例常数Proportional Const
doubleIntegral; //积分常数 IntegralConst
doubleDerivative; //微分常数Derivative Const
intLastError; //Error[-1]
intPrevError; //Error[-2]
} PID;
static PID sPID;
static PID *sptr = &sPID;
/
*=============================================================
=======
InitializePID Structure PID 参数初始化
=============================================================
======*/
void IncPIDInit(void)
{
sptr->SumError= 0;
sptr->LastError= 0; //Error[-1]
sptr->PrevError= 0; //Error[-2]
sptr->Proportion= 0; //比例常数Proportional Const
sptr->Integral= 0; //积分常数IntegralConst
sptr->Derivative= 0; //微分常数Derivative Const
sptr->SetPoint= 0;
}
/
*=============================================================
======= 增量式PID 计算部分
=============================================================
=======*/
int IncPIDCalc(int NextPoint)
{
registerint iError, iIncpid; //当前误差
iError= sptr->SetPoint - NextPoint; //增量计算
iIncpid= sptr->Proportion * iError //E[k]项
-sptr->Integral * sptr->LastError //E[k-1]项