What is PID? The classic controller behind stable control loops
Atlasbot · 16/8/2026 · 11 min read
Knowing the current motor speed (thanks to the encoder) is not enough — an automatic controller is needed to decide how much to adjust the PWM so that the actual speed is close to the desired speed, even when the load is constantly changing. PID (Proportional–Integral–Derivative) is the classic and most popular controller for this problem — simple to understand, effective in most practical applications.
Key concepts
The core idea of every control loop: continuously calculate error between the desired value (setpoint) and the actual measured value, and then use that error to decide the next control signal.
error = setpoint - measured_value
PID combines three components, each responding to errors in a different way:
- P (Proportional) — proportional to the current error: the larger the error, the stronger the reaction. Simple, but used alone often leaves a steady-state error — never returning to the exact setpoint.
- I (Integral) — accumulates errors over time: if the errors are small but persistent (P alone is not strong enough to completely eliminate them), part I will gradually accumulate and push the system to the correct setpoint.
- D (Derivative) — reacts according to the speed of change of the error: if the error is decreasing very quickly (about to overshoot the setpoint), D will "brake" less to avoid overshooting.
In summary: P pulls quickly to the target but leaves residual errors · I eliminates residual errors but reacts slowly and easily causes fluctuations if too strong · D smooths, prevents overshoot but is sensitive to measurement noise.
How it works
setpoint ──►(+) ┌─── P: Kp × error ───┐
│ error │ │
measured ──►(-)┴──────────►├─── I: Ki × Σerror ──┼──► (+) ──► PWM ──► motor
│ │ │
└─── D: Kd × Δerror ──┘ │
│
◄──────────── Encoder measures real speed ─────────────┘
Formula to calculate PID output per cycle (usually run in Timer interrupt, fixed frequency like 100Hz or 1kHz):
float error = setpoint - measured_speed;
integral += error * dt;
float derivative = (error - previous_error) / dt;
float output = Kp * error + Ki * integral + Kd * derivative;
previous_error = error;
set_motor_pwm(output); // Apply the calculated value to the motor
The three constants Kp, Ki, Kd must be tuned for each specific system — there is no universal set of numbers for all motors. The most common tuning is to gradually increase Kp until the system oscillates slightly, reduce it a bit, then add Ki to eliminate residual errors, and finally add Kd if needed to reduce oscillations — this process often takes a lot of trial and error on real hardware, because theoretical simulations rarely perfectly match the actual friction and inertia of the motor.
Technical details
Formulas
Correctly apply the PID formula above with specific data to clearly see how much each component contributes to the final output:
output = Kp×error + Ki×integral + Kd×derivative
VD: Kp=2.0, Ki=0.5, Kd=0.1
setpoint = 100 RPM, measured = 85 RPM → error = 15
integral (accumulated from before) = 40
derivative (error change -5 compared to the previous cycle, dt=0.01s) = (15-20)/0.01 = -500
output = 2.0×15 + 0.5×40 + 0.1×(-500)
= 30 + 20 - 50 = 0
This example shows that component D can cancel out almost all the contributions of P and I when the error is decreasing very quickly - exactly the "brake" role against overshoot mentioned in the Main Concepts section, although at first glance it seems paradoxical (the error is still positive 15 but the output is close to 0).
Parameters
The PID loop running frequency (sample rate) needs to be fast enough compared to the kinematics characteristics of the system being controlled — running too slow causes the controller to "react late" to actual changes:
| Control loop type | Typical PID frequency |
|---|---|
| DC motor speed (using encoder) | 100Hz – 1kHz |
| Position/angle (eg: balancing 2 wheel robot) | 100 – 500Hz |
| Temperature (thermal system, slow change) | 1 – 10Hz is enough |
A more systematic method for adjusting Kp/Ki/Kd than the trial-and-error method mentioned above is Ziegler-Nichols — increase Kp (Ki=Kd=0) until the oscillating system continuously stabilizes, record the "critical Kp" and the period of oscillation, then calculate Kp/Ki/Kd according to the standardized formula table based on those two values.
Practical applications
In addition to keeping the motor speed mentioned throughout the article, PID is also commonly used to keep it heading of the robot following the compass/IMU — setpoint is the desired direction angle, the measured value is the actual angle from the IMU, the PID output is the speed difference between the two wheels (which wheel needs to rotate faster for the robot to self-correct in the right direction). In more complex differential 2-wheel robots, it is often used Nested PID (cascade): 1 position PID loop (setpoint is distance/destination) creates speed setpoint for 1 internal speed PID loop — each loop only solves exactly 1 problem, much easier to adjust than combining into a single PID set.
Practical example
#include <stdio.h>
int main() {
float Kp = 2.0, Ki = 0.5, Kd = 0.1;
float setpoint = 100.0;
float measured = 85.0;
float integral = 40.0;
float previous_error = 20.0;
float dt = 0.01;
float error = setpoint - measured;
integral += error * dt;
float derivative = (error - previous_error) / dt;
float output = Kp*error + Ki*integral + Kd*derivative;
printf("error = %.1f\n", error);
printf("P = %.1f, I = %.1f, D = %.1f\n", Kp*error, Ki*integral, Kd*derivative);
printf("output = %.1f\n", output);
return 0;
}
Output:
error = 15.0
P = 30.0, I = 20.2, D = -500.0
output = -449.8
The large negative result of output (although error is still positive) clearly illustrates the actual risk of component D when derivative is too large — if the output value is not limited to the correct PWM range before applying to the motor, the motor can be ordered to reverse suddenly even though it is in the right direction, an error that is difficult to diagnose without printing out each P/I/D component separately for debugging as in the example. hey.
Common mistakes
- Integral windup (integral windup) — when the motor has reached the maximum PWM limit but has not yet caught up with the setpoint, part I continues to accumulate indefinitely, until the error reverses, the system takes a long time to "discharge" all this excess accumulation, causing serious overshoot — it is necessary to limit (clamp) the integral value within a reasonable range.
- "Derivative kick" when changing setpoint suddenly — instantaneous setpoint change (eg from 0 to 100 RPM immediately) causes
errorto jump in 1 cycle, the D component calculated according to the derivative of the error also jumps, creating an abnormal control pulse — a common solution is to calculate the derivative with respect to measured value get instead of following error. - Forget to clamp the output to the correct PWM range — as shown in the example above, the calculated output can go far beyond the valid PWM range (0-100% or negative/positive for rotation direction) — always check and limit the output before applying it to the motor driver.
dtis not constant between calculations — if the PID loop does not run at a fixed frequency (e.g. placed inloop()instead of a Timer interrupt),dtactually fluctuates with other processing times, causing inconsistent system behavior between runs even with the same Kp/Ki/Kd set.
Conclusion
PID is a simple yet powerful controller for most stability needs in robotics — from holding motor speed, holding direction, to more complex nested loops for position. Understanding the role of each P/I/D component and the classic traps (integral windup, derivative kick) helps avoid most confusing behavior when first tuning PID on real hardware. This is also the penultimate article in the Motor Control section - the last article will summarize and compare the learned motor speed control methods.
Get new articles and lessons by email
When a new technical article or course module is published, Atlas Robotics sends you a short email. No spam.
Unsubscribe any time with the link in each email. See our Privacy policy.