求一下增量式和位置式PID的C语言程序1
发布网友
发布时间:2023-10-15 01:21
我来回答
共1个回答
热心网友
时间:2024-02-19 00:24
增量式PID:
typedef struct{
float scope; //输出限幅量
float aim; //目标输出量
float real_out; //实际输出量
float Kp;
float Ki;
float Kd;
float e0; //当前误差
float e1; //上一次误差
float e2; //上上次误差
}PID_Type;
#define min(a, b) (a<b? a:b)
#define max(a, b) (a>b? a:b)
#define limiter(x, a, b) (min(max(x, a), b))
#define exchange(a, b, tmp) (tmp=a, a=b, b=tmp)
#define myabs(x) ((x<0)? -x:x)
float pid_acc(PID_Type *pid)
{
float out;
float ep, ei, ed;
pid->e0 = pid->aim - pid->real_out;
ep = pid->e0 - pid->e1;
ei = pid->e0;
ed = pid->e0 - 2*pid->e1 + pid->e2;
out = pid->Kp*ep + pid->Ki*ei + pid->Kd*ed;
out = limiter(out, -pid->scope, pid->scope);
pid->e2 = pid->e1;
pid->e1 = pid->e0;
return out;
}
位置式PID:
typedef struct{
float scope; //输出限幅量
float aim; //目标输出量
float real_out; //反馈输出量
float Kp;
float Ki;
float Kd;
float Sum;
float e0; //当前误差
float e1; //上一次误差
}PID_Type;
#define max(a, b) (a>b? a:b)
#define min(a, b) (a<b? a:b)
#define limiter(x, a, b) (min(max(x, a), b))
float pid_pos(PID_Type *p)
{
float pe, ie, de;
float out = 0;
p->e0 = p->aim - p->real_out; //计算当前误差
p->Sum += p->e0; //误差积分
de = p->e0 - p->e1; //误差微分
pe = p->e0;
ie = p->Sum;
p->e1 = p->e0;
out = pe*(p->Kp) + ie*(p->Ki) + de*(p->Kd);
out = limiter(out, -p->scope, p->scope); //输出限幅
return out;
}
亲手移植到我的stm32小车上 调试3个参数后正常使用。