1、电机与驱动 一个简单的 PIDPID#include /* common defines and macros */#include “derivative.h“ /* derivative-specific definitions */#include /定义 PID参数#define VV_KPVALUE 3 /比例#define VV_KIVALUE 40 /积分#define VV_KDVALUE 3 /微分#define VV_MAX 10000 /返回的最大值,是 pwm的周期值#define VV_MIN 0#define VV_DEADLINE 0X08 /速度 PID,设置死
2、区范围typedef struct PID /定义数法核心数据signed int vi_Ref; /速度 PID,速度设定值signed int vi_FeedBack; /速度 PID,速度反馈值signed long vi_PreError; /速度 PID,前一次,速度误差,vi_Ref - vi_FeedBacksigned long vi_PreDerror; /速度 PID,前一次,速度误差之差,d_error-PreDerror;unsigned int v_Kp; /速度 PID,Ka = Kpunsigned int v_Ki; /速度 PID,Kb = Kp * ( T
3、/ Ti )unsigned int v_Kd; /速度 PID,signed long vl_PreU; /电机控制输出值PID;PID sPID; / PID Control Structurevoid PIDInit(void) sPID.vi_Ref = 0 ; /速度设定值sPID.vi_FeedBack = 0 ; /速度反馈值sPID.vi_PreError = 0 ; /前一次,速度误差,vi_Ref - vi_FeedBacksPID.vi_PreDerror = 0 ; /前一次,速度误差之差,d_error-PreDerror;sPID.v_Kp = VV_KPVALUE
4、;sPID.v_Ki = VV_KIVALUE;sPID.v_Kd = VV_KDVALUE;sPID.vl_PreU = 0 ; /电机控制输出值 unsigned int v_PIDCalc( PID *pp )signed long error,d_error,dd_error; error = (signed long)(pp-vi_Ref - pp-vi_FeedBack); / 偏差计算 d_error = error - pp-vi_PreError;dd_error = d_error - pp-vi_PreDerror;pp-vi_PreError = error; /存储当
5、前偏差pp-vi_PreDerror = d_error;if( ( error -VV_DEADLINE ) ); /设置调节死区/速度 PID计算pp-vl_PreU += (signed long)( pp - v_Kp * d_error + pp - v_Ki * error + pp-v_Kd*dd_error);else if( pp-vl_PreU = VV_MAX ) /速度 PID,防止调节最高溢出pp-vl_PreU = VV_MAX;else if( pp-vl_PreU vl_PreU = VV_MIN; else;return ( pp-vl_PreU ); / 返回预调节占空比 void main(void) /* put your own code here */InitMCu(); IncPIDInit();int g_CurrentVelocity=0; /全局变量也初始化int g_Flag=0; /全局变量也初始化EnableInterrupts;While(1)if (g_Flagg_Flagfor(;) _FEED_COP(); /* feeds the dog */ /* loop forever */* please make sure that you never leave main */