Feel the code is good, will definitely use in the future, invasion and deletion
#include <reg52.h>#include<string.h>//memset function header file in C language#defineunsigned int UINTtypedefstructPID {DoubleSetPoint;//set Target desired valueDoubleproportion;//proportional constant Proportional ConstDoubleIntegral;//integral constant integral ConstDoublederivative;//differential constant derivative ConstDoubleLastError;//Error[-1]DoublePreverror;//Error[-2]DoubleSumerror;//Sums of Errors}pid;
/*================================================
====================================================pid Calculation Part =======================
==============================================================================*/ DoublePidcalc (PID *pp,Doublenextpoint) { DoubleDerror, Error; Error= pp->setpoint-nextpoint;//deviationsPp->sumerror + = Error;//pointsDerror = error-pp->lasterror;//Current DifferentialPp->preverror = pp->LastError; PP->lasterror =Error; return(Pp->proportion * Error//Scale Item+ pp->integral * Pp->sumerror//Integral Items+ pp->derivative * Derror//Differential Term); }/*=======================================================
============================================= Initialize PID Structure pid parameter Initialization =============
========================================================================================*/ voidPidinit (PID *PP) {memset (PP,0,sizeof(PID)); }
/*======================================================
============================================== Main program ===================
==================================================================================*/ DoubleSensor (void)//Dummy Sensor Function{ return 100.0; } //void Actuator (double rdelta)//Dummy Actuator Function//{} voidMainvoid) {PID SPID;//PID Control StructureDoubleROut;//PID Response (Output)DoubleRIn;//PID Feedback (Input)Pidinit (&SPID);//Initialize StructureSpid.proportion =0.5;//Set PID coefficientsSpid.integral =0.5; Spid.derivative=0.0; Spid.setpoint=100.0;//Set PID setpoint for(;;) {// Mock up of PID processing rIn= Sensor ();//Read InputROut = Pidcalc (&spid,rin);//Perform PID interation//Actuator (rOut);//Effect Needed Changes} }
PID control algorithm C source code