├── README.md ├── pid.c └── pid.h /README.md: -------------------------------------------------------------------------------- 1 | Incremental PID Control 2 | ============================= 3 | 增量式PID算法C语言实现
4 | C implementation of Incremental PID Control 5 | -------------------------------------------------------------------------------- /pid.c: -------------------------------------------------------------------------------- 1 | #include "pid.h" 2 | #include 3 | 4 | #define MAXOUT 1000 //输出最大值 5 | 6 | PID sPID; 7 | static pPID sptr; 8 | 9 | void IncPIDInit(void) 10 | { 11 | sptr = &sPID; 12 | sptr->SetPoint = 700; //设定值 13 | sptr->BitMove = 0u; //返回结果比例 14 | 15 | sptr->LastError = 0u; //前2次误差值 16 | sptr->PrevError = 0u; //前1次误差值 17 | 18 | sptr->Proportion = 3.0f; //比例 19 | sptr->Integral = 0.0f; //积分 20 | sptr->Derivative = 0.0f; //微分 21 | 22 | sptr->iError = 0; //当前误差 23 | sptr->iIncpid = 0; //增量误差 24 | 25 | sptr->Uk = 0; //输出返回值 26 | } 27 | 28 | int IncPIDCalc(int NextPoint) 29 | { 30 | //当前误差 31 | sptr->iError = sptr->SetPoint - NextPoint; 32 | //增量误差 33 | sptr->iIncpid = sptr->Proportion * sptr->iError - sptr->Integral * sptr->LastError 34 | + sptr->Derivative * sptr->PrevError; 35 | //存储误差,用于下次计算 36 | sptr->PrevError = sptr->iError; 37 | sptr->LastError = sptr->LastError; 38 | 39 | sptr->Uk += sptr->iIncpid; 40 | 41 | //输出值限幅 42 | if (sptr->Uk>>sptr->BitMove >= MAXOUT) 43 | { 44 | sptr->Uk = MAXOUT; 45 | } 46 | else if(sptr->Uk>>sptr->BitMove <= 0u) 47 | { 48 | sptr->Uk = 0; 49 | } 50 | else sptr->Uk = sptr->Uk>>sptr->BitMove; 51 | 52 | return (sptr->Uk); 53 | } 54 | -------------------------------------------------------------------------------- /pid.h: -------------------------------------------------------------------------------- 1 | #ifndef __PID_H 2 | #define __PID_H 3 | 4 | typedef struct PID 5 | { 6 | int SetPoint; 7 | 8 | unsigned char BitMove; 9 | 10 | float Proportion; 11 | float Integral; 12 | float Derivative; 13 | 14 | int iError; 15 | int iIncpid; 16 | 17 | int LastError; 18 | int PrevError; 19 | 20 | int Uk; 21 | } PID, *pPID; 22 | 23 | extern PID sPID; 24 | 25 | void IncPIDInit(void); 26 | int IncPIDCalc(int NextPoint); 27 | 28 | #endif 29 | --------------------------------------------------------------------------------