为什么该段代码 输出值不变啊
程序代码:
#include <stdio.h> #include <Windows.h> typedef struct { float kp; //P float ki; //I float kd; //D float imax; //积分限幅 float out_p; //KP输出 float out_i; //KI输出 float out_d; //KD输出 float out; //pid输出 float integrator; //< 积分值 float last_error; //< 上次误差 float last_derivative;//< 上次误差与上上次误差之差 float last_t; //< 上次时间 }pid_param_t; float constrain_float(float amt, float low, float high) { return ((amt)<(low)?(low):((amt)>(high)?(high):(amt))); } /*! * @brief pid参数初始化函数 * * @param 无 * * @return 无 * * @note 无 * * @see 无 * * @date 2020/6/8 */ void PidInit(pid_param_t * pid) { pid->kp = 0; pid->ki = 0; pid->kd = 0; pid->imax = 0; pid->out_p = 0; pid->out_i = 0; pid->out_d = 0; pid->out = 0; pid->integrator= 0; pid->last_error= 0; pid->last_derivative = 0; pid->last_t = 0; } /*! * @brief pid位置式控制器输出 * * @param pid pid参数 * @param error pid输入误差 * * @return PID输出结果 * * @note 无 * * @see 无 * * @date 2020/6/8 */ float PidLocCtrl(pid_param_t * pid, float error) { /* 累积误差 */ pid->integrator += error; /* 误差限幅 */ constrain_float(pid->integrator, -pid->imax, pid->imax); pid->last_error = error; pid->out_p = pid->kp * error; pid->out_i = pid->ki * pid->integrator; pid->out_d = pid->kd * (error - pid->last_error); pid->out = pid->out_p + pid->out_i + pid->out_d; return pid->out; } int main () { pid_param_t pid1; int T=100; PidInit(&pid1); pid1.kp = 0.2; pid1.ki = 0.1; PidLocCtrl(&pid1, 100); while(pid1.out != 100) { printf("pid1.out %f\n",pid1.out); Sleep(T);//延时ms } }
而这段代码 为什么输出值能够趋向预定值呢
程序代码:
struct _pid{ float SetSpeed; //定义设定值 float ActualSpeed; //定义实际值 float err; //定义偏差值 float err_last; //定义上一个偏差值 float Kp,Ki,Kd; //定义比例、积分、微分系数 float voltage; //定义电压值(控制执行器的变量) float integral; //定义积分值 }pid; void PID_init(){ printf("PID_init begin \n"); pid.SetSpeed=0.0; pid.ActualSpeed=40.0; pid.err=0.0; pid.err_last=0.0; pid.voltage=0.0; pid.integral=0.0; pid.Kp=0.2; pid.Ki=0.1; pid.Kd=0; printf("PID_init end \n"); } float PID_realize(float speed){ pid.SetSpeed=speed; pid.err=pid.SetSpeed-pid.ActualSpeed; pid.integral+=pid.err; pid.voltage=pid.Kp*pid.err+pid.Ki*pid.integral+pid.Kd*(pid.err-pid.err_last); pid.err_last=pid.err; pid.ActualSpeed=pid.voltage*1.0; return pid.voltage; } int main(){ PID_init(); int count=0; while(count<100) { float speed=PID_realize(200.0); printf("%f\n",speed); count++; } return 0; }