Understanding PID Code Without Using a Library.

hello,

For academic reasons I must write a PID section in my project, this forbids the use of a library. I am familiar with the principles and use of PIDs from many drones but have never coded one.

The overall goal is to take in up to 4096 possible steps from a mems magnetometer but that range will be restricted somewhat. This feeds into the PID code. From the PID output, a motor will be driven via PWM and H-bridge so clockwise and counterclockwise needs to be accounted for.

Im looking at this site: Improving the Beginner’s PID – Introduction « Project Blog

but Im not understanding some code below:

/*working variables*/
unsigned long lastTime;
double Input, Output, Setpoint;
double errSum, lastErr;
double kp, ki, kd;
void Compute()
{
   /*How long since we last calculated*/
   unsigned long now = millis();
   double timeChange = (double)(now - lastTime);
  
   /*Compute all the working error variables*/
   double error = Setpoint - Input;
   errSum += (error * timeChange);
   double dErr = (error - lastErr) / timeChange;
  
   /*Compute PID Output*/
   Output = kp * error + ki * errSum + kd * dErr;
  
   /*Remember some variables for next time*/
   lastErr = error;
   lastTime = now;
}
  
void SetTunings(double Kp, double Ki, double Kd)
{
   kp = Kp;
   ki = Ki;
   kd = Kd;
}

What does this part do?

void SetTunings(double Kp, double Ki, double Kd)
{
   kp = Kp;
   ki = Ki;
   kd = Kd;
}

it seems like this should be at the top if thats where im loading my chosen values.

Thank you for any help, this will be a long-running thread for my benefit but I think for others too.

-Patrick

What does this part do?

It just copies values supplied by the calling program to the internal parameters. It does not matter where that code is "located".

If you are required to write your own code, keep in mind that a PID loop can be written in just a few lines. A good general introduction to PID should give you all the information you need. There are many on line.

This link has some nice simple PID code

To my mind there is too much window-dressing around PID. It is basically a very simple concept.

...R