1. //***************************************************** 2. //定義PID結(jié)構(gòu)體 3. //***************************************************** 4. typedef struct PID 5. { 6. int SetPoint; //設(shè)定目標(biāo)Desired Value 7. double Proportion; //比例常數(shù)Proportional Const 8. double Integral; //積分常數(shù)Integral Const 9. double Derivative; //微分常數(shù)Derivative Const 10. int LastError; //Error[-1] 11. int PrevError; //Error[-2] 12. } PID; 13. //***************************************************** 14. //定義相關(guān)宏 15. //***************************************************** 16. #define P_DATA 100 17. #define I_DATA 0.6 18. #define D_DATA 1 19. #define HAVE_NEW_VELOCITY 0X01 20. //***************************************************** 21. //聲明PID實(shí)體 22. //***************************************************** 23. static PID sPID; 24. static PID *sptr = &sPID; 25. //***************************************************** 26. //PID參數(shù)初始化 27. //***************************************************** 28. void IncPIDInit(void) 29. { 30. sptr->LastError = 0; //Error[-1] 31. sptr->PrevError = 0; //Error[-2] 32. sptr->Proportion =P_DATA; //比例常數(shù)Proportional Const 33. sptr->Integral =I_DATA; //積分常數(shù)Integral Const 34. sptr->Derivative =D_DATA; //微分常數(shù)Derivative Const 35. sptr->SetPoint =100; 目標(biāo)是100 36. } 37. //***************************************************** 38. //增量式PID控制設(shè)計(jì) 39. //***************************************************** 40. int IncPIDCalc(int NextPoint) 41. { 42. int iError, iIncpid; //當(dāng)前誤差 43. iError = sptr->SetPoint- NextPoint; //增量計(jì)算 44. iIncpid =sptr->Proportion * iError //E[k]項(xiàng) 45. - sptr->Integral * sptr->LastError //E[k-1]項(xiàng) 46. + sptr->Derivative * sptr->PrevError; //E[k-2]項(xiàng) 47. sptr->PrevError =sptr->LastError; //存儲(chǔ)誤差,用于下次計(jì)算 48. sptr->LastError =iError; 49. return(iIncpid); //返回增量值 50. }
|