定义一个结构体如下:
typedef struct{
double setpoint; //设定值
double proportiongain; //比列系数 p 测试 设置为0.2
double integralgain; //积分系数 i 测试 设置为0.015
double derivativegain; //微分系数 d 测试 设置为 0.2
double lasterror; //前一拍偏差
double result; //输出值
double integral; //积分值 误差值之和
}PID;
//调整函数
void PIDRegulation(PID * vPID,double processValue){ //此算法出现问题的原因是在操作结构体的其他元素时,会不知名导致另外元素的值发生
//改变解决办法是将里面的可能发生改变的量用其它变量来代替
double thisError; //定义误差
aa=0.2;
bb=0.015;
cc=0.2;
thisError = vPID->setpoint-processValue; //计算误差
vPID->integral += thisError; //误差求和
vPID->result=vPID->proportiongain*thisError+vPID->integralgain*vPID->integral+vPID->derivativegain*(thisError-vPID->lasterror);
vPID->lasterror = thisError;
}
//初始化函数
void PID_init(float set,float p,float i,float d,float error,float sumi,PID *tempPID){
tempPID->setpoint = set;
tempPID->proportiongain = p;
tempPID->integralgain = i;
tempPID->derivativegain = d;
tempPID->lasterror = error;
tempPID->integral = sumi;
tempPID->result = 0;
}
//产生结构体变量
PID *testPID;
//赋值
PID_init(2000,0.2,0.015,0.2,0,0,testPID);
//调用调整函数
PIDRegulation(testPID,testPID->result); //在此函数运行完之后,结构体中不该改变的数据都被改变了 |