AnyLearn
All lessons
Roboticsintermediate

PID Controllers

Master the proportional-integral-derivative controller: what each term fixes, the PID equation, integral windup, a discrete Python implementation, and a Ziegler-Nichols tuning guide for real loops.

Updated · AI-authored, review-gated · how lessons are made

Progress1 / 8

The three terms — intuition first

PID stands for Proportional-Integral-Derivative. Each term fixes a specific failure mode of the basic proportional controller:

  • P (Proportional): Acts on the current error. Big error → big correction. Provides responsiveness. Alone it leaves a steady-state offset (the motor needs some error to produce some torque).
  • I (Integral): Acts on accumulated error over time. As long as any error remains, the integral term keeps growing, pushing the output until it reaches exactly the setpoint. Kills steady-state error — but can cause slow windup.
  • D (Derivative): Acts on the rate of change of error. If the error is shrinking fast, D applies a brake to prevent overshoot. It damps oscillations. Think of it as predicting where the error is heading.

The three terms work together: P drives toward the setpoint, I eliminates residual bias, D smooths the approach.

Sign in free to save your progress and earn certificates.

Full lesson text

All 8 steps on one page, for reading, reference, and search.

Show

1. The three terms — intuition first

PID stands for Proportional-Integral-Derivative. Each term fixes a specific failure mode of the basic proportional controller:

  • P (Proportional): Acts on the current error. Big error → big correction. Provides responsiveness. Alone it leaves a steady-state offset (the motor needs some error to produce some torque).
  • I (Integral): Acts on accumulated error over time. As long as any error remains, the integral term keeps growing, pushing the output until it reaches exactly the setpoint. Kills steady-state error — but can cause slow windup.
  • D (Derivative): Acts on the rate of change of error. If the error is shrinking fast, D applies a brake to prevent overshoot. It damps oscillations. Think of it as predicting where the error is heading.

The three terms work together: P drives toward the setpoint, I eliminates residual bias, D smooths the approach.

2. The PID equation

The continuous-time PID control law is:

u(t)=Kp e(t)  +  Ki∫0te(τ) dτ  +  Kd e˙(t)u(t) = K_p\, e(t) \;+\; K_i \int_0^t e(\tau)\,d\tau \;+\; K_d\, \dot{e}(t)

where e(t)=r(t)−y(t)e(t) = r(t) - y(t) is the error, and KpK_p, KiK_i, KdK_d are the three gains to tune.

In transfer-function form, the PID controller is:

C(s)=Kp+Kis+KdsC(s) = K_p + \frac{K_i}{s} + K_d s

The 1/s1/s term is the Laplace-domain integrator; the ss term is the differentiator. Notice that pure differentiation amplifies high-frequency noise (large ss → large magnitude at high frequency). In practice, the D term is almost always filtered: Kds/(1+s/N)K_d s / (1 + s/N) where NN is the derivative filter coefficient (typically 5–20), limiting how much noise the D term amplifies.

3. What each gain actually does to the response

Here is how tuning each gain shifts the step response — the core of practical PID tuning:

Increase...Rise timeOvershootSettling timeSteady-state errorStability
KpK_pDecreasesIncreasesSmall changeDecreasesDegrades
KiK_iDecreasesIncreasesIncreasesEliminatesDegrades more
KdK_dSmall changeDecreasesDecreasesNo effectImproves (if noise is low)

The table reveals the fundamental tension: everything that speeds up the response (higher KpK_p, KiK_i) also reduces stability margins. KdK_d is the one gain that both damps overshoot and improves stability — but only if the sensor is clean. With noisy encoders, a large KdK_d amplifies noise into the actuator and causes chatter.

4. Integral windup and anti-windup

Integral windup is the most common PID failure in real hardware. It occurs when the actuator saturates — e.g., the motor hits its maximum voltage — but the integral keeps accumulating error. By the time the output finally reaches the setpoint, the integrator is enormous, causing a massive overshoot that takes a long time to unwind.

Example: a robot arm overshoots a target by 40° and then slowly creeps back, ringing for 10 seconds. Windup is usually the culprit.

Anti-windup strategies:

  1. Clamping: Stop integrating when the output saturates (if abs(u) >= u_max: don't integrate).
  2. Back-calculation: Feed the saturation error back into the integrator at a rate 1/Tt1/T_t, actively unwinding it.
  3. Conditional integration: Only integrate when ∣e∣<|e| < threshold (near the setpoint).

Every production PID implementation should have anti-windup. Without it, actuator saturation will cause overshoots that look mysterious until you trace the integrator state.

5. Discrete-time PID implementation in Python

Real controllers run at fixed sample rate TsT_s (e.g., 1 ms). The integral becomes a running sum; the derivative becomes a finite difference:

class PID:
    def __init__(self, Kp, Ki, Kd, dt, u_max=float('inf'), N=10):
        self.Kp, self.Ki, self.Kd = Kp, Ki, Kd
        self.dt = dt
        self.u_max = u_max      # actuator limit for anti-windup
        self.N = N              # derivative filter coefficient
        self._integral = 0.0
        self._prev_e = 0.0
        self._d_filt = 0.0      # filtered derivative state

    def step(self, r, y):
        e = r - y
        # Anti-windup: only integrate if not saturated
        if abs(self._prev_u if hasattr(self, '_prev_u') else 0) < self.u_max:
            self._integral += e * self.dt
        # Filtered derivative: d/dt filtered via first-order IIR
        raw_d = (e - self._prev_e) / self.dt
        self._d_filt += self.dt * self.N * (raw_d - self._d_filt)
        u = self.Kp * e + self.Ki * self._integral + self.Kd * self._d_filt
        u = max(-self.u_max, min(self.u_max, u))  # clamp
        self._prev_e = e
        self._prev_u = u
        return u

This 20-line class is the skeleton of every PID loop you will ever deploy. The key choices: sample period TsT_s, actuator limits, and the derivative filter bandwidth N/TsN/T_s Hz.

6. Ziegler-Nichols tuning: a practical sketch

When you have a real plant and no model, Ziegler-Nichols gives starting gains in under 10 minutes:

Step 1 — Ultimate gain KuK_u: Disable I and D, ramp up KpK_p until the output oscillates continuously (barely unstable). That gain is KuK_u; measure the oscillation period TuT_u.

Step 2 — Apply the table:

Controller typeKpK_pKiK_iKdK_d
P only0.5 Ku0.5\, K_u——
PI0.45 Ku0.45\, K_u0.54 Ku/Tu0.54\, K_u / T_u—
PID0.6 Ku0.6\, K_u1.2 Ku/Tu1.2\, K_u / T_u0.075 KuTu0.075\, K_u T_u

Ziegler-Nichols deliberately targets ~25 % overshoot — that is not a bug, it is the design intent. For lower overshoot, scale KpK_p down to 0.3–0.4 KuK_u. For slow, non-oscillatory processes (chemical reactors, temperature loops), the step-response / reaction-curve variant is safer than forcing oscillations. ZN is a starting point, not an endpoint.

7. Feed-forward: reducing the load on feedback

A pure feedback PID corrects errors after they occur. A feedforward term predicts the required control effort and applies it proactively — before the error builds up.

For a robot joint, gravity torque is predictable from kinematics:

u(t)=Kpe+Ki∫e dt+Kde˙⏟feedback+G^(q)⏟gravity feedforwardu(t) = \underbrace{K_p e + K_i \int e\,dt + K_d \dot{e}}_{\text{feedback}} + \underbrace{\hat{G}(q)}_{\text{gravity feedforward}}

With a good gravity model G^\hat{G}, the feedback terms only need to correct model errors — they can be tuned to small, safe gains. This is the architecture used in almost every high-performance robot arm: a physics-based feedforward handles the bulk of the control effort, and a lightweight PID closes the remaining gap.

The pattern extends beyond gravity: velocity feedforward for tracking moving setpoints, friction compensation, inertia decoupling. Feedforward and feedback are complementary, not competing strategies.

8. PID in practice: common failure modes

After tuning thousands of loops, experienced engineers recognise these signatures:

Slow oscillation at steady state — KiK_i too high or sample rate too low. Reduce KiK_i by half and check.

Fast, high-frequency chatter — KdK_d is amplifying encoder quantization noise. Add derivative filter or reduce KdK_d.

Large overshoot that takes forever to settle — integral windup. Verify anti-windup is active and the integrator is clamped during saturation.

Sluggish response that doesn't improve with more KpK_p — you may be fighting friction. Add a small deadband near zero error, or add a friction compensator.

Response changes with operating point — the plant is nonlinear (most real plants are). Consider gain scheduling (different PID gains at different speeds/loads) or switch to a model-based approach like state-space with state feedback.

Check your understanding

The lesson ends with a 5-question quiz. Take it in the player above to see your score.

  1. A motor PID loop holds position perfectly at rest but always has a 2° offset when a constant load is applied. Which gain should you increase?
    • $K_p$, because the proportional term sets the steady-state output.
    • $K_i$, because the integral term eliminates steady-state error.
    • $K_d$, because the derivative term compensates for external disturbances.
    • All three simultaneously using the Ziegler-Nichols formula.
  2. After a large step command, your robot arm overshoots by 50° and slowly creeps back over 8 seconds. The actuator was at its voltage limit during the entire transient. What is the most likely cause?
    • $K_d$ is too large, causing the derivative term to overshoot.
    • $K_p$ is too small, causing a sluggish initial response.
    • Integral windup: the integrator accumulated a large value while the actuator was saturated.
    • The sample rate is too low, causing aliasing in the derivative term.
  3. Why is the pure derivative term $K_d s$ almost always replaced by $K_d s / (1 + s/N)$ in practice?
    • The filtered form eliminates the need for anti-windup circuitry.
    • The pure derivative has infinite gain at high frequency, amplifying sensor noise into the actuator.
    • The filtered form ensures the D term contributes to steady-state error elimination.
    • The filter makes the controller causal by adding a small delay.
  4. In the Ziegler-Nichols tuning method, what is the 'ultimate gain' $K_u$?
    • The maximum gain the actuator can physically produce.
    • The proportional gain at which the closed-loop system begins to oscillate continuously.
    • The gain that minimises integral of squared error.
    • The gain corresponding to a phase margin of exactly 45°.
  5. You add a gravity feedforward term $\hat{G}(q)$ to your PID arm controller. What is the primary benefit?
    • It eliminates the need for a position sensor.
    • It allows the feedback gains to be smaller, improving noise immunity and stability margins.
    • It automatically tunes $K_p$, $K_i$, and $K_d$ based on the robot model.
    • It converts the discrete PID into a continuous-time controller.

Related lessons

AI
intermediate

Learned Simulators for Robots and Cars, and How World Models Fail

How world models train and test robots and driving systems, and where they break. Covers learning to walk in an hour with DayDreamer, driving world models, ranking robot policies in a video simulator, compounding error in code, model exploitation and its defences, hallucinated physics, and why evaluation is the hardest part.

10 steps·~15 min
Robotics
intermediate

How Self-Driving Safety Is Argued and Measured

What it takes to show a self-driving system is safe enough: SAE automation levels and operational design domains, why test miles alone cannot prove safety, how crash rates are compared with human benchmarks, why disengagement counts mislead, and how safety cases, crash reporting and remote assistance fit together.

10 steps·~15 min
Robotics
intermediate

Modular Stacks vs End-to-End Driving

Two ways to build a self-driving system: a pipeline of separately engineered modules, or one network trained from sensors to trajectory. Covers imitation learning, causal confusion, why open-loop scores mislead, joint designs like UniAD, foundation-model drivers, and what each approach costs when you must prove it safe.

11 steps·~17 min
Robotics
intermediate

Predicting Road Users, Planning, and Control

How a self-driving car turns tracked objects into motion: forecasting several possible futures for every road user, choosing a trajectory that is safe across them, and steering it with a controller. Covers scene representations, interaction, Frenet-frame planning, and why rule-based planners remain strong baselines.

10 steps·~15 min