/*====================================================================================================
这是从网上找来的一个比较典型的PID处理程序,在运用单片机作为操控cpu时,请稍作简化,详细的PID
参数必须由详细方针经过试验确认。因为单片机的处理速度和ram资源的约束,一般不选用浮点数运算,
而将一切参数悉数用整数,运算到最后再除以一个2的N次方数据(相当于移位),作相似定点数运算,可
大大提高运算速度,依据操控精度的不同要求,当精度要求很高时,留意保存移位引起的“余数”,做好余
数补偿。这个程序仅仅一般常用pid算法的根本架构,没有包括输入输出处理部分。
=====================================================================================================*/
#include
#include
/*====================================================================================================
PID Function
The PID (份额、积分、微分) function is used in mainly
control applications. PIDCalc performs one iteration of the PID
algorithm.
While the PID function works, main is just a dummy program showing
a typical usage.
=====================================================================================================*/
typedef struct PID {
double SetPoint; // 设定方针 Desired Value
double Proportion; // 份额常数 Proportional Const
double Integral; // 积分常数 Integral Const
double Derivative; // 微分常数 Derivative Const
double LastError; // Error[-1]
double PrevError; // Error[-2]
double SumError; // Sums of Errors
} PID;
/*====================================================================================================
PID核算部分
=====================================================================================================*/
double PIDCalc( PID *pp, double NextPoint )
{
double dError,
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 // 微分项
);
}
/*====================================================================================================
Initialize PID Structure
=====================================================================================================*/
void PIDInit (PID *pp)
{
memset ( pp,0,sizeof(PID));
}
/*====================================================================================================
Main Program
=====================================================================================================*/
double sensor (void) // Dummy Sensor Function
{
return 100.0;
}
void actuator(double rDelta) // Dummy Actuator Function
{}
void main(void)
{
PID sPID; // PID Control Structure
double rOut; // PID Response (Output)
double rIn; // PID Feedback (Input)
PIDInit ( &sPID ); // Initialize Structure
sPID.Proportion = 0.5; // Set PID Coefficients
sPID.Integral = 0.5;
sPID.Derivative = 0.0;
sPID.SetPoint = 100.0; // Set PID Setpoint
for (;;) { // Mock Up of PID Processing
rIn = sensor (); // Read Input
rOut = PIDCalc ( &sPID,rIn ); // Perform PID Interation
actuator ( rOut ); // Effect Needed Changes
}
}