demo_pid.c

来自「OMRON CP1H的新功能试验程序」· C语言 代码 · 共 72 行

C
72
字号
    #include<string.h>
/*====================================================================================================
     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
   {rDelta=0;}

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
               }
     }

⌨️ 快捷键说明

复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?