Steppe School PID, Live PID in C (article)

PID controller, live

This is a drone arm on a test stand. Two motors, one PID controller. Grab the arm, change the gains, and watch what each term of the equation does.

e = 0.0°
target 0°
angle 0.0°
50%
50%
Drag the arm to push it. Drag the background to look around.
error e = target − angle = 0.0 − 0.0 = 0.0°
PHow big is the error now?
Kp × e = 6.0 × 0.0 = 0.0
IHow long has the error been there?
Ki × ∫e dt = 8.0 × 0.0 = 0.0
DHow fast is it changing?
Kd × de/dt = 2.00 × 0.0 = 0.0
output u = P + I + D = 0.0% left motor 50% · right motor 50%
Angle angle target
What the controller sends P I D u

Try this, in order

  1. The more error we have, the more the motors push. But nothing slows the arm down, so it swings for a long time.

  2. D looks at how fast the angle changes and brakes. The swinging is gone.

  3. Now the arm stops below the target. P needs some error to hold the weight. This is the steady-state error.

  4. I sums the error over time. It keeps growing until the error is zero.

  5. Look at the motors. D amplifies the noise. Lower Kd to about 1 and it calms down.

  6. Anti-windup is off. Hold the arm down for a few seconds and let go. The integral became huge, so the arm overshoots a lot. Turn anti-windup on and try again.

The same thing in C

These are the lines that run inside the microcontroller, with the numbers from the simulator right now.

float error = reference - measurement;        // 0.0
float P = pid->Kp * error;                    // 0.0
pid->integral += error * dt;                  // 0.0
float I = pid->Ki * pid->integral;            // 0.0
float D = pid->Kd * (error - pid->prev_error) / dt;  // 0.0
float output = P + I + D;                     // 0.0

The simulator takes the derivative of the measurement and filters it a little, so D does not jump when the target changes.

Read the full article: PID implementation in C · Get the free PID C library