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.

Not signed in โ€” your progress and quiz score won't be saved.
Lesson 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.

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
advanced

Reinforcement Learning in 2026: Where It Ships and Where It Stalls

An honest map of RL in 2026 โ€” the domains where it actually reaches production (LLM post-training, robotics policies, ad bidding, RLHF, reasoning models) and the places where it still cannot reliably cross the lab-to-deployment gap.

12 stepsยท~18 minยทaudio
Robotics
beginner

Closing the Loop: Microcontrollers and Feedback

Open-loop control is a guess; closed-loop control is a conversation. Learn why feedback transforms an unreliable robot into a reliable one, how the read-compute-actuate cycle works, what microcontrollers and single-board computers each do best, and why loop timing is just as critical as the algorithm running inside it.

10 stepsยท~15 minยทaudio
Robotics
beginner

Sensors: How Robots Perceive

A robot is only as good as what it can measure. Explore the full sensor toolkit โ€” encoders, IMUs, ultrasonic rangefinders, LiDAR, cameras, and force/torque sensors โ€” and learn the four metrics that determine whether a sensor is fit for purpose: resolution, range, noise, and sampling rate.

10 stepsยท~15 minยทaudio
Robotics
beginner

What Is a Robot? Anatomy and the Sense-Plan-Act Loop

Strip any robot to its bones and you find three things: sensors that gather data, a controller that thinks, and actuators that move. Learn how these pieces fit together through the Sense-Plan-Act paradigm, why reactive control sometimes beats planning, and what makes a Roomba and a welding arm both qualify as robots.

10 stepsยท~15 minยทaudio