Starting PID with Basic Knowledge of How to do it already

Hey, I’ve read through Introduction To PID Control Loops - Google Docs in order to figure out PID further, but when it comes to programming it, I’m not sure where to start, do you think you could help?

1 Like

The first thing to consider is your application. PID uses a control loop using a sensor value to control something. Identify what your input and output will be. (For example an IMU angle and turning the drive base). Then set up your variables (kp,ki,kp,error,prevError,sum,target, accuracy). After that create a while loop that exits when you are close to your target. Then, create the output everytime in the loop using kp x error + ki x sum + kd x (error-prevError). Create your prev values using prevError=error and sum+=error. Add a wait inside of the loop after you create your previous values. Finally you need to turn your values.

pseudo code
int PID(double target) { 
   double kp = 1; 
   double ki = .1; 
   double kd = .01; 
   double sum = 0; 
   double prevError = 0; 
   double error = target - sensor value; 
   double accuracy = .1; 
   while(true){ 
   double speed; 
   while (fabs(error) > accuracy) { 
     error = targetAngle - sensor value; 
     speed = (error * kp) + (ki * sum) + (kd * (error - prevError));
      motor.spin(fwd, speed, pct);

    wait(10, msec); 
     prevError = error; 
     sum += error; 
   }
motor.stop();
}

This is a fine implementation of PID ideals. You might Google PID windup. This code lacks some protection against real world issues – if you were to set the desired target a long way from the current location, you could get some unhappy behavior.

I like writing code starting from first principles. The beginning approach could work well. There are some well known pitfalls. This is an area that people generally first encounter in graduate level control systems classes, so expect a few speed bumps.

1 Like