首先,就增量式PID的函數(shù)進(jìn)行編寫:
頭文件,全局變量與宏定義如下:
#include "stdio.h"
#include "math.h"
void pid_init();//PID參數(shù)初始化
float pid_realise(float speed);//實(shí)現(xiàn)PID算法
#define value 1400.0
首先定義結(jié)構(gòu)體pid的相關(guān)內(nèi)容,后面將根據(jù)PID里面的相關(guān)參數(shù)進(jìn)行修改調(diào)整,觀察波形情況。
struct {
float set_speed;//設(shè)定速度
float actual_speed;//實(shí)際速度
float error;//偏差
float error_next;//上一個(gè)偏差
float error_last;//上上一個(gè)偏差
float kp,ki,kd;//定義比例,積分,微分參數(shù)
}pid;
將PID結(jié)構(gòu)體中的參數(shù)進(jìn)行初始化設(shè)置,其中的參數(shù)是我經(jīng)過(guò)調(diào)整后的參數(shù)
void pid_init()
{
pid.set_speed = 0;
pid.actual_speed = 10000.0;//原始值0.0
pid.error = 0.0;
pid.error_next = 0.0;
pid.error_last = 0.0;
//可調(diào)節(jié)PID 參數(shù)。使跟蹤曲線慢慢接近階躍函數(shù)200.0 //
pid.kp = 0.33333;//原始值0.2
pid.ki = 0.2111;//原始值0.1
pid.kd = 0.1;//原始值0.3
}
接下來(lái)實(shí)現(xiàn)PID實(shí)現(xiàn)的過(guò)程函數(shù):
float pid_realise(float speed)//實(shí)現(xiàn)pid
{ float increment_speed;//增量
pid.set_speed = speed;//設(shè)置目標(biāo)速度
pid.error = pid.set_speed - pid.actual_speed;
increment_speed = pid.kp*(pid.error-pid.error_next)+pid.ki*pid.error+\
pid.kd*(pid.error-2*pid.error_next+pid.error_last);//增量計(jì)算公式
pid.actual_speed+= increment_speed;
pid.error_last = pid.error_next;//下一次迭代
pid.error_next = pid.error;
return pid.actual_speed;
}
接著就是主函數(shù),主函數(shù)這里將進(jìn)行設(shè)置,邏輯如下:初始化參數(shù),進(jìn)行運(yùn)算,運(yùn)算次數(shù)設(shè)置為400次,可以提高,因?yàn)檎{(diào)整后的參數(shù),后面又有break可以跳出while循環(huán)因此不需要在意這里,接下來(lái)就是不斷判斷期望值與實(shí)際值誤差書否在5以內(nèi)
int main()
{ int count = 1;
int num = 0;
int type;
pid_init();
while(count<400)//進(jìn)行400次 PID 運(yùn)算可以提高,使初始值從0開始接近200.0
{
float speed = pid_realise(value);//設(shè)定值設(shè)定為200.0
type=abs(speed-value);
printf("%f\n",speed);//
if( type <= 5) ///判斷每次的誤差是否在5以內(nèi)
{
num++;
if(num==6)
{
printf("run number is %d\r\n",count);
break;
}
else count++;
}
else count++;
}
}
運(yùn)行函數(shù)之后得到如下圖所示的曲線,可以看到,假設(shè)單位階躍相應(yīng)的過(guò)程中期望值發(fā)生改變,假設(shè)初始值為7000,要調(diào)整到理想值按照當(dāng)前參數(shù)大約需要47次變換。


審核編輯:湯梓紅
-
PID
+關(guān)注
關(guān)注
37文章
1479瀏覽量
86972 -
函數(shù)
+關(guān)注
關(guān)注
3文章
4365瀏覽量
63872 -
編寫
+關(guān)注
關(guān)注
0文章
29瀏覽量
8574
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
淺析位置式PID與增量式PID算法
教你用C語(yǔ)言實(shí)現(xiàn)位置式PID和增量式PID
請(qǐng)問(wèn)如何調(diào)節(jié)增量式pid?
增量式pid分析及參數(shù)整定

增量與位置PID
增量式pid參數(shù)調(diào)整公式及策略
使用單片機(jī)和Arduino實(shí)現(xiàn)增量式PID位置式PID算法和PID庫(kù)免費(fèi)下載

PID:智能小車入門(位置式和增量式)

評(píng)論