🔥码云GVP开源项目 12k star Uniapp+ElementUI 功能强大 支持多语言、二开方便! 广告
# Hpid.c ```c #include "Hpid.h" PID_t *mthis ; PID_t* GetPid(PID_t *pid) { mthis = pid ; return mthis; } int HPID_Run(int current) { int ans = 0; mthis->current = current ; mthis->e0 = mthis->e1; mthis->e1 = mthis->e2; mthis->e2 = mthis->target - mthis->current ; ans = mthis -> Kp * (mthis->e2 - mthis->e1) ; //P ans += mthis->Ki * mthis->e2 ; //I ans += mthis->Kd * (mthis->e2 -2*mthis->e1 + mthis->e0) ; //D ans = ans / mthis->A ; return ans ; } void HPID_Reset() { mthis->e2 = 0; mthis->e1 = 0; mthis->e0 = 0; } void HPID_Init(PID_t *pid ){ pid->A = 1; pid->output = 0; pid->current = 0; pid->target = 0; pid->Kp=0; pid->Ki= 0 ; pid->Kd = 0; pid->Run = HPID_Run; pid->Reset = HPID_Reset ; } ``` # Hpid.h ```c #ifndef _SRC_HPID_H_ #define _SRC_HPID_H_ typedef struct _PID_t_{ int A ; //系数,计算值最后缩小的倍数 int output ; //输出值 int current; //当前值 int target; //设定值 int Kp; //比例系数 int Kd; //积分系数 int Ki; //微分系数 int e0,e1,e2 ; int ( *Run)(int); //进行增量式PID计算 void (*Reset)(); //复位 }PID_t; void HPID_Init(PID_t * pid) ; PID_t* GetPid(PID_t *pid) ; #endif ``` # main.cpp ```cpp #include "iostream" #include "Hpid.h" using namespace std ; int main() { PID_t pid1 ; HPID_Init(&pid1) ; pid1.target = 1; pid1.Ki = 10; cout << GetPid(&pid1)->Run(2); } ```