專注電子技術(shù)學(xué)習(xí)與研究
當(dāng)前位置:單片機(jī)教程網(wǎng) >> MCU設(shè)計實例 >> 瀏覽文章

單片機(jī)PID算法實現(xiàn)

作者:韓冰   來源:本站原創(chuàng)   點擊數(shù):  更新時間:2013年11月28日   【字體:
在avr單片機(jī)上實現(xiàn)的100%通過測試,用單片機(jī)調(diào)的倒立擺非常穩(wěn)定.
#include <stdio.h>
#include<math.h>

 
struct _pid
{
int pv; //integer that contains the process value 過程量
int sp; //*integer that contains the set point   設(shè)定值
float integral; // 積分值
float pgain;
float igain;
float dgain;
int deadband;    //死區(qū)
int last_error;
};

 
struct _pid warm,*pid;
int process_point, set_point,dead_band;
float p_gain, i_gain, d_gain, integral_val,new_integ;;

 
void pid_init(struct _pid *warm, int process_point, int set_point)
{
struct _pid *pid;
pid = warm;
pid->pv = process_point;
pid->sp = set_point;
}

 

 
void pid_tune(struct _pid *pid, float p_gain, float i_gain, float d_gain, int dead_band)
{
pid->pgain = p_gain;
pid->igain = i_gain;
pid->dgain = d_gain;
pid->deadband = dead_band;
pid->integral= integral_val;
pid->last_error=0;
}

 

 

 
void pid_setinteg(struct _pid *pid,float new_integ)
{
pid->integral = new_integ;
pid->last_error = 0;
}

 

 
void pid_bumpless(struct _pid *pid)
{
pid->last_error = (pid->sp)-(pid->pv);  //設(shè)定值與反饋值偏差
}

 

 

 

 
float pid_calc(struct _pid *pid)
int err;
float pterm, dterm, result, ferror;

 
// 計算偏差
err = (pid->sp) - (pid->pv);

 
// 判斷是否大于死區(qū)
if (abs(err) > pid->deadband)
{
ferror = (float) err;   //do integer to float conversion only once 數(shù)據(jù)類型轉(zhuǎn)換

 
// 比例項
pterm = pid->pgain * ferror;

 
if (pterm > 100 || pterm < -100)
{
pid->integral = 0.0;
}
else
{
// 積分項
pid->integral += pid->igain * ferror;

 

 
if (pid->integral > 100.0)
{
pid->integral = 100.0;
}

 
else if (pid->integral < 0.0)
pid->integral = 0.0;

 
}

 
// 微分項
dterm = ((float)(err - pid->last_error)) * pid->dgain;

 
result = pterm + pid->integral + dterm;
}
else
result = pid->integral; // 在死區(qū)范圍內(nèi),保持現(xiàn)有輸出

 
// 保存上次偏差
pid->last_error = err;

 
return (result);
}
 
//----------------------------------------------
參數(shù)說明:
p_gain = (float)(5.2);//比例系數(shù)
i_gain = (float)(0.77);//積分系數(shù)
d_gain = (float)(0.18);//微分系數(shù)
process_point為設(shè)定的穩(wěn)定值
display_value為系統(tǒng)輸出值
process_point為傳感器傳入當(dāng)前值


 
函數(shù)調(diào)用示例:
float display_value;
int count=0;
pid = &warm;

 
process_point = 30;
set_point = 40;

 
dead_band = 2;

 
integral_val =(float)(0.01);
scanf("%d",&process_point);
// 設(shè)定PV,SP值
pid_init(&warm, process_point, set_point);

 
// 初始化PID參數(shù)值
pid_tune(&warm, p_gain,i_gain,d_gain,dead_band);

 
// 初始化PID輸出值
pid_setinteg(&warm,0.0);
//pid_setinteg(&warm,30.0);

 
pid_bumpless(&warm);

 
display_value = pid_calc(&warm);

 
printf("%f\n", display_value);

 
關(guān)閉窗口

相關(guān)文章