在avr單片機上實現的100%通過測試,用單片機調的倒立擺非常穩定.
#include <stdio.h>
#include<math.h>
struct _pid
{
int pv; //integer that contains the process value 過程量
int sp; //*integer that contains the set point 設定值
float integral; // 積分值
float pgain;
float igain;
float dgain;
int deadband; //死區
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); //設定值與反饋值偏差
}
float pid_calc(struct _pid *pid)
{·
int err;
float pterm, dterm, result, ferror;
// 計算偏差
err = (pid->sp) - (pid->pv);
// 判斷是否大于死區
if (abs(err) > pid->deadband)
{
ferror = (float) err; //do integer to float conversion only once 數據類型轉換
// 比例項
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; // 在死區范圍內,保持現有輸出
// 保存上次偏差
pid->last_error = err;
return (result);
}
//----------------------------------------------
參數說明:
p_gain = (float)(5.2);//比例系數
i_gain = (float)(0.77);//積分系數
d_gain = (float)(0.18);//微分系數
process_point為設定的穩定值
display_value為系統輸出值
process_point為傳感器傳入當前值
函數調用示例:
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);
// 設定PV,SP值
pid_init(&warm, process_point, set_point);
// 初始化PID參數值
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);