## 新闻中心

EEPW首页 > 嵌入式系统 > 设计应用 > PID算法C18程序的实现

# PID算法C18程序的实现

PID 计算资源需求

DS=Pdu(k)+I t/ti(uk)+ D TD/T duk+du(k-1)

puk-i *T/TI*uk+d*(uk-2* uk-1 + uk-2)

#define PID_TYPE int

`struct pid_unit { PID_TYPE pid_sens[3];   // 用来保存 UK UK-1 UK-2 三个时刻的输出偏差PID_TYPE pid_cpid[3];   // 当然是 P  I  D 三个参数咯PID_TYPE pid_dpid[3];   // P 部分计算值 I部分计算值 D 部分计算值 这三个值相加就是PID 的输出};初始化PIDvoid pid_init(struct pid_unit *unit, PID_TYPE p,             PID_TYPE i,            PID_TYPE d)              { unit->pid_cpid[0] = p; //PID 比例系数 初始化 没得说 哈unit->pid_cpid[1] = i; unit->pid_cpid[2] = d; unit->pid_dpid[0] = 0;//P  i  d 个个部分都假定为0  不过实际也是0#24unit->pid_dpid[1] = 0; //unit->pid_dpid[2] = 0; //unit->pid_sens[0] = 0; // 当前差值unit->pid_sens[1] = 0; //unit->pid_sens[2] = 0; //}`

unit->pid_dpid[0] = unit->pid_sens[0] * unit->pid_cpid[0]; //就是P*UK

unit->pid_sens[1] = unit->pid_sens[0];
unit->pid_sens[0] = input;

unit->pid_dpid[1] = unit->pid_sens[0] * unit->pid_cpid[1] * time;

unit->pid_dpid[1] += unit->pid_sens[0] * unit->pid_cpid[1] * time;

ΔU=U(k)-U(k-1)=Kp*[e(k)-e(k-1)]+Ki*e(k)+Kd*[e(k)-2*e(k-1)+e(k-2)]

D部分 Kd*[e(k)-2*e(k-1)+e(k-2)

unit->pid_dpid[2] = ((unit->pid_sens[0] - 2*unit->pid_sens[1]+unit->pid_sens[2])/time) *unit->pid_cpid[2];

unit->pid_dpid[0] + unit->pid_dpid[1] + unit->pid_dpid[2];

`PID_TYPE pid_control(struct pid_unit *unit,   PID_TYPE input,          PID_TYPE time)            { // adjust the FIFO preserving the sensor data unit->pid_sens[1] = unit->pid_sens[0]; unit->pid_sens[0] = input; // calculate each pid variable unit->pid_dpid[0]  =  unit->pid_sens[0] * unit->pid_cpid[0]; unit->pid_dpid[1] =  unit->pid_sens[0] * unit->pid_cpid[1] * time; unit->pid_dpid[2]  = (unit->pid_sens[0] - unit->pid_sens[1])/time *unit->pid_cpid[2]; return unit->pid_dpid[0] +  unit->pid_dpid[1] + unit->pid_dpid[2]; } `