这个程序只是一般常用pid算法的基本架构,没有包含输入输出处理部分。
//PID结构体定义
typedefstructPID{
doubleSetPoint;//设定目标Desiredvalue
doubleProportion;//比例常数ProportionalConst
doubleIntegral;//积分常数IntegralConst
doubleDerivative;//微分常数DerivativeConst
doubleLastError;//Error[-1]
doublePrevError;//Error[-2]
doubleSumError;//SumsofErrors
}PID;
//PID计算部分
doublePIDCalc(PID*pp,doubleNextPoint)
{
doubledError,
Error;
Error=pp->SetPoint-NextPoint;//偏差
pp->SumError+=Error;//积分
dError=pp->LastError-pp->PrevError;//当前微分
pp->PrevError=pp->LastError;
pp->LastError=Error;
return(pp->Proportion*Error//比例项
+pp->Integral*pp->SumError//积分项
+pp->Derivative*dError//微分项
);
}
//初始化PID结构
voidPIDInit(PID*pp)
{
memset(pp,0,sizeof(PID));
}
//输入通道和输出通道
doublesensor(void)//DummySensorFunction
{
return100.0;
}
voidactuator(doublerDelta)//DummyActuatorFunction
{
}
//主函数
voidmain(void)
{
PIDsPID;//PIDControlStructure
doublerOut;//PIDResponse(Output)
doublerIn;//PIDFeedback(Input)
PIDInit(&sPID);//InitializeStructure
sPID.Proportion=0.5;//SetPIDCoefficients
sPID.Integral=0.5;
sPID.Derivative=0.0;
sPID.SetPoint=100.0;//SetPIDSetpoint
for(;;){//MockUpofPIDProcessing
rIn=sensor();//ReadInput
rOut=PIDCalc(&sPID,rIn);//PerformPIDInteration
actuator(rOut);//EffectNeededChanges
}
}