/*-------------------------------------------
2 位置型PID C实现(控制电机转速)
--------------------------------------------*/
//(1)定义PID 结构体变量
struct pid
{
float SetSpeed; //设定速度
float ActualSpeed; //实际值
float err; //k,定义偏差值
float err_last; //k-1,上一个偏差值
float err_last_next; //k-2
float Kp, Ki, Kd; //p,i,d系数
}pid;
int main()
{
int count = 0;
cout << "Please begin \n";
pid_value_init();
while (count < 100)
{
float speed = PID_realize(200.0);
cout << "value is " << speed << endl;
count++;
}
system("pause");
}
//(3) 控制算法注意:这里用了最基本的算法实现形式,没有考虑死区问题,
//没有设定上下限,只是对公式的一种直接的实现,后面的介绍当中还会逐渐的对此改进。
float PID_realize(float speed)
{
float incrementSpeed;
pid.SetSpeed = speed;
pid.err = pid.SetSpeed - pid.ActualSpeed;
incrementSpeed = pid.Kp * (pid.err -pid.err_last ) + pid.Ki*pid.err + pid.Kd*(pid.err -2* pid.err_last + pid.err_last_next);
pid.ActualSpeed += incrementSpeed;
pid.err_last = pid.err;
pid.err_last_next = pid.err_last;
return pid.ActualSpeed;
}
//(2) 初始化变量
void pid_value_init(void)
{
cout << "pid_value_init begin \n" << endl;
system("pause");
pid.SetSpeed = 0;
pid.ActualSpeed = 0;
pid.err = 0;
pid.err_last = 0;
pid.err_last_next = 0;
pid.Kp = 0.1;
pid.Ki = 0.15;
pid.Kd = 0.1;
cout << "pid_value_init end \n" << endl;
system("pause");
}