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.
Try this, in order
The more error we have, the more the motors push. But nothing slows the arm down, so it swings for a long time.
D looks at how fast the angle changes and brakes. The swinging is gone.
Now the arm stops below the target. P needs some error to hold the weight. This is the steady-state error.
I sums the error over time. It keeps growing until the error is zero.
Look at the motors. D amplifies the noise. Lower Kd to about 1 and it calms down.
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