当编码器的定时器,每隔10ms反馈一次编码器测出的实际速度后,调用PID函数,求解输出给电机驱动板的PWM值,然后通过Set_Pwm函数进行设置,以此控制电机转速。- void Velocity_PID(int TargetVelocity,int CurrentVelocity,PID_InitDefStruct* p)
- {
- if(p->PID_is_Enable == 1)
- {
- int En = TargetVelocity - CurrentVelocity;//误差值
-
- p->Un += p->Velcity_Kp*(En - p->En_1) + p->Velcity_Ki*En + p->Velcity_Kd*(En - 2*p->En_1 + p->En_2);//增量式PID
-
- p->En_2=p->En_1;
- p->En_1=En;
-
- p->PWM = p->Un;
-
- /*输出限幅*/
- if(p->PWM>p->Ur) p->PWM=p->Ur;
- if(p->PWM<-p->Ur) p->PWM=-p->Ur;
- }
- else
- {
- PID_Init(p);
- }
-
- }
|