PID公式的推導過程及實現(xiàn)代碼


n0(t)是要穩(wěn)定的值
n(t)是當前輸出值
e(t) = n0(t) - n(t)
一、模擬PID控制原理
這個公式網絡上很好找:


二、數字PID控制
由于模擬的微積分運算對應計算機來說是不太好寫代碼的,所以要利用采樣將數據離散化
于是公式就可以轉換為:

其中T為采樣時間,由于T之類的參數是常量,所以將Kp乘入公式中可以轉換成另一種寫法
這個公式叫位置式算法
由于要不斷的累加ej,增加了計算量,所以這個公式又可以轉換為增量式算法:

然后u(k) = u(k-1) + u
三、參數的整定
先將Ti設置為無窮大,Td設置為0,調節(jié)Kp
然后再調節(jié)Ti,最后是Td
四、實現(xiàn)代碼
typedef struct PID
{
int SetPoint; //設定目標 Desired Value
longSumError; //誤差累計
double Proportion; //比例常數 Proportional Cons
double Integral; //積分常數 Integral Const
double Derivative; //微分常數 Derivative Const
double Integral; //積分常數 Integral Const
double Derivative; //微分常數 Derivative Const
int LastError; //Error[-1]
int PrevError; //Error[-2]
} PID;
/*******************************************************************************
* 函數名稱 : IncPIDCalc
* 函數描述 : 增量式 PID 控制計算
* 函數輸入 : int 當前位置
* 函數輸出 : 無
*函數返回 : 增量式PID結果
*******************************************************************************/
int IncPIDCalc(int NextPoint)
{
int iError, iIncpid;
//當前誤差
iError = sptr->SetPoint - NextPoint;
//增量計算
iIncpid = sptr->Proportion * iError //E[k]項
- sptr->Integral * sptr->LastError //E[k-1]項
+ sptr->Derivative * sptr->PrevError; //E[k-2]項
//存儲誤差,用于下次計算
sptr->PrevError = sptr->LastError;
sptr->LastError = iError;
//返回增量值
return(iIncpid);
}
int PrevError; //Error[-2]
} PID;
/*******************************************************************************
* 函數名稱 : IncPIDCalc
* 函數描述 : 增量式 PID 控制計算
* 函數輸入 : int 當前位置
* 函數輸出 : 無
*函數返回 : 增量式PID結果
*******************************************************************************/
int IncPIDCalc(int NextPoint)
{
int iError, iIncpid;
//當前誤差
iError = sptr->SetPoint - NextPoint;
//增量計算
iIncpid = sptr->Proportion * iError //E[k]項
- sptr->Integral * sptr->LastError //E[k-1]項
+ sptr->Derivative * sptr->PrevError; //E[k-2]項
//存儲誤差,用于下次計算
sptr->PrevError = sptr->LastError;
sptr->LastError = iError;
//返回增量值
return(iIncpid);
}
/*******************************************************************************
* 函數名稱 : LocPIDCalc
* 函數描述 : 位置式 PID 控制計算
* 函數輸入 : int 當前位置
* 函數輸出 : 無
*函數返回 : 位置式PID結果
*******************************************************************************/
int LocPIDCalc(int NextPoint)
{
int iError,dError;
* 函數名稱 : LocPIDCalc
* 函數描述 : 位置式 PID 控制計算
* 函數輸入 : int 當前位置
* 函數輸出 : 無
*函數返回 : 位置式PID結果
*******************************************************************************/
int LocPIDCalc(int NextPoint)
{
int iError,dError;
iError = sptr->SetPoint - NextPoint; //偏差
sptr->SumError += iError; //積分
dError = iError - sptr->LastError; //微分
sptr->LastError = iError;
sptr->SumError += iError; //積分
dError = iError - sptr->LastError; //微分
sptr->LastError = iError;
return(sptr->Proportion * iError //比例項
+ sptr->Integral * sptr->SumError //積分項
+ sptr->Derivative * dError); //微分項
}
+ sptr->Integral * sptr->SumError //積分項
+ sptr->Derivative * dError); //微分項
}
評論