Stage 07 · Lesson 08/15

Control Systems & PID · Lesson 08

Combining PID

Est. 60–75 min

Why

Why P, I and D work best as a team

In Lessons 5–7 you met each term alone. P gave speed but left a leftover error and, with a high gain, overshoot. I removed the leftover error but added overshoot. D calmed the overshoot but could not touch the leftover error and amplified noise. Put together, each covers the others’ weakness. *Modern Robotics* (Eq. 11.23) writes the full PID law for a robot joint and calls it a common feedback controller; the Michigan *Control Tutorials* add that PID is widely used because it is easy to understand and quite effective.

By the end of this lesson you will be able to: write PID as one equation and as clean code; build a small, reusable PID class with output limits, a clamped integral and derivative on measurement; compare P, PI, PD and PID on the same joint; read which term does the work at each moment of a move; and run the same PID on the Arduino light keeper.

A diagram of an industrial flow control loop: a controller box with setpoint, process value and controller output, a flow transmitter in a pipe sending the flow rate back, and a flow control valve receiving the valve position
An industrial process control loop: the controller compares the set point (SP) with the process value (PV) from a flow transmitter and sends an output (CO) to a valve. In factories, the controller in this box is often a PID.Photo: Dougsim · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

How the three terms share the work

u = Kp × e + Ki × ∫ e dt + Kd × de/dt

  • P — reacts to the error now (the push).
  • I — reacts to the error accumulated so far (the memory).
  • D — reacts to how fast the error is changing (the brakes).
  • *Modern Robotics* Eq. 11.23: τ = Kp θe + Ki ∫θe dt + Kd θ̇e.
Results from pid_control.py — same joint, same Kp = 0.04 N·m/°
ModeKiKdPeakFinalError at 10 sSettles within ±2°
P00131.90°88.75°1.25°4.53 s
PI0.0020133.33°89.50°0.50° (still shrinking)3.22 s
PD00.00893.89°88.75°1.25°1.20 s
PID0.0020.00895.35°90.07°−0.07°1.34 s
PID (Ki too big)0.010.008100.96°90.45°−0.45°4.49 s

PD is the fastest to get close, but stays 1.25° short. PI removes most of the error but swings wildly. PID gets both: small overshoot, quick settling and almost no leftover error. The last row is a warning: with Ki five times bigger, the integral builds up during the rise, so the joint overshoots more and creeps back slowly. More is not always better.

Who does the work, and when?

Inside the PID run (from pid_control.py, torques in N·m)
TimeAngleP termI termD termWhat is happening
0.05 s2°3.520.01−0.60P pushes hard; D already braking as speed builds
0.30 s42°1.920.04−1.48Moving fast — D brakes strongly
0.60 s84°0.260.06−0.67Nearly there; P almost gone
1.00 s95°−0.210.060.03Small overshoot; P pulls back
10 s90.07°−0.0030.0530.000At rest: I holds the gravity load (0.05 N·m)

This table is the whole lesson in one picture. P does the heavy lifting at the start, D acts only while the joint moves, and I quietly takes over the steady load. At rest, P and D are almost zero and the I term carries the 0.05 N·m that gravity needs.

A real PID is more than the formula

  • Output limits — clamp the command to what the actuator can do (±4 N·m here, 0–255 PWM on Arduino).
  • Anti-windup — clamp the integral so it cannot exceed the output range (Lesson 6; more in Lesson 11).
  • Derivative on measurement — no kick when the setpoint jumps (Lesson 7).
  • Fixed loop rate and real dt — so the gains mean the same thing every tick (Lesson 4).
  • Logging — print P, I and D separately; you can’t tune what you can’t see.
A green circuit board from inside a panel-mount controller, with an NEC microcontroller chip in the middle and white connectors on the left
Inside an OMRON panel-mount PID controller: the main board with its NEC 78K0-series microcontroller (photo description). A dedicated PID box is still a small computer running a loop like the one you write in this lesson.Photo: Phiarc · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Visual

Visualise it: P vs PI vs PD vs PID

Switch between **P, PI, PD and PID** on the same plant. Compare overshoot, settling time and leftover error — and see why the full team usually wins.

Interactive · PID visualizer

PID terms cheat sheet: P speed, I removes SSE, D damps

Setpoint 70° · final θ 69.1° · |SSE| 0.94° · constant load on

Teaching model: Kp↑ snappier (overshoot risk); Ki↑ reduces steady-state error under load; Kd↑ damps the edge.

Code lab

Code lab: a reusable PID class

pid_control.py packs everything into one small PID class with output limits, a clamped integral and derivative on measurement. It then runs P, PI, PD and PID on the same joint and prints who does the work during the PID move. Run it with python3 pid_control.py.

pid_control.py · Python
# pid_control.py - putting P, I and D together in one small, reusable PID class.
# Same joint as Lessons 5-7: J*accel = torque - B*speed - LOAD   (angles in degrees)

J, B, LOAD, TAU_MAX = 0.002, 0.004, 0.05, 4.0
SETPOINT, DT, T_END = 90.0, 0.001, 10.0


class PID:
    def __init__(self, kp, ki, kd, out_min, out_max):
        self.kp, self.ki, self.kd = kp, ki, kd
        self.out_min, self.out_max = out_min, out_max
        self.integral = 0.0
        self.prev_meas = None

    def update(self, setpoint, measured, dt):
        error = setpoint - measured
        p = self.kp * error
        # integral, clamped so the I term alone can never exceed the output limits
        self.integral += error * dt
        if self.ki > 0:
            lim = self.out_max / self.ki
            self.integral = max(-lim, min(lim, self.integral))
        i = self.ki * self.integral
        # derivative on MEASUREMENT: no kick when the setpoint jumps
        d_meas = 0.0 if self.prev_meas is None else (measured - self.prev_meas) / dt
        self.prev_meas = measured
        d = -self.kd * d_meas
        out = max(self.out_min, min(self.out_max, p + i + d))
        return out, p, i, d


def run(kp, ki, kd):
    pid = PID(kp, ki, kd, -TAU_MAX, TAU_MAX)
    angle = speed = t = 0.0
    log = []
    while t < T_END:
        torque, p, i, d = pid.update(SETPOINT, angle, DT)
        speed += (torque - B * speed - LOAD) / J * DT
        angle += speed * DT
        t += DT
        log.append((t, angle, p, i, d))
    return log


def settle_time(log, band=2.0):
    last_out = 0.0
    for t, a, *_ in log:
        if abs(SETPOINT - a) > band:
            last_out = t
    return last_out if last_out < T_END - 0.01 else None


print("Same joint, gravity load 0.05 N.m, setpoint 90 deg\n")
print(f"{'mode':>5} {'Kp':>6} {'Ki':>6} {'Kd':>6} {'peak':>9} {'final':>9} {'error':>7} {'settle(+/-2deg)':>16}")
for name, kp, ki, kd in (("P", 0.04, 0, 0), ("PI", 0.04, 0.002, 0),
                         ("PD", 0.04, 0, 0.008), ("PID", 0.04, 0.002, 0.008),
                         ("PID*", 0.04, 0.01, 0.008)):
    log = run(kp, ki, kd)
    peak = max(a for _, a, *_ in log)
    final = log[-1][1]
    st = settle_time(log)
    st_txt = f"{st:.2f} s" if st is not None else "never"
    print(f"{name:>5} {kp:>6} {ki:>6} {kd:>6} {peak:>8.2f}° {final:>8.2f}° {SETPOINT-final:>6.2f}° {st_txt:>16}")

print("PID* = same PID with Ki five times bigger: the integral grows during the rise and causes a slow tail.")
print("\nInside the PID run (Kp 0.04, Ki 0.002, Kd 0.008) - who does the work?")
log = run(0.04, 0.002, 0.008)
print(f"{'t (s)':>6} {'angle':>8} {'P term':>8} {'I term':>8} {'D term':>8}  (N.m)")
for t_pick in (0.05, 0.3, 0.6, 1.0, 2.0, 5.0, 10.0):
    t, a, p, i, d = min(log, key=lambda r: abs(r[0] - t_pick))
    print(f"{t_pick:>6.2f} {a:>7.2f}° {p:>8.3f} {i:>8.3f} {d:>8.3f}")
print("\nP pushes hard at the start, D brakes while the joint moves fast,")
print("and I slowly takes over the 0.05 N.m that gravity needs.")

Output (run with python3 pid_control.py)

Same joint, gravity load 0.05 N.m, setpoint 90 deg

 mode     Kp     Ki     Kd      peak     final   error  settle(+/-2deg)
    P   0.04      0      0   131.90°    88.75°   1.25°           4.53 s
   PI   0.04  0.002      0   133.33°    89.50°   0.50°           3.22 s
   PD   0.04      0  0.008    93.89°    88.75°   1.25°           1.20 s
  PID   0.04  0.002  0.008    95.35°    90.07°  -0.07°           1.34 s
 PID*   0.04   0.01  0.008   100.96°    90.45°  -0.45°           4.49 s
PID* = same PID with Ki five times bigger: the integral grows during the rise and causes a slow tail.

Inside the PID run (Kp 0.04, Ki 0.002, Kd 0.008) - who does the work?
 t (s)    angle   P term   I term   D term  (N.m)
  0.05    2.05°    3.521    0.009   -0.600
  0.30   42.11°    1.923    0.044   -1.476
  0.60   83.58°    0.260    0.059   -0.666
  1.00   95.24°   -0.210    0.057    0.033
  2.00   89.82°    0.007    0.054   -0.003
  5.00   90.09°   -0.003    0.053    0.000
 10.00   90.07°   -0.003    0.053    0.000

P pushes hard at the start, D brakes while the joint moves fast,
and I slowly takes over the 0.05 N.m that gravity needs.

Try it: switch between P, PI, PD and PID modes on the same plant. Find the mode that gives small overshoot and zero leftover error.

Interactive · PID visualizer

PID terms cheat sheet: P speed, I removes SSE, D damps

Setpoint 70° · final θ 69.1° · |SSE| 0.94° · constant load on

Teaching model: Kp↑ snappier (overshoot risk); Ki↑ reduces steady-state error under load; Kd↑ damps the edge.

Simulator

Try it in the simulator

Simulator · Control

PID tuning on a DC-motor position plant

Tune Kp, Ki and Kd, add an actuator limit and anti-windup, and read rise time, overshoot and settling from the step response.

Loading simulator…

Formulas used

  • e = r − y
  • u = Kp·e + Ki·Σe·Δt − Kd·Δy/Δt
  • J·θ̈ + b·θ̇ = K·u − τ_load
  • |u| ≤ u_max
  • P-only steady-state error with load: e_ss = τ_load / (K·Kp)

Model & limits

Linear DC-motor position model (inertia J, viscous friction b, torque gain K), no backlash or static friction. Teaching values, not a specific motor.

Real world

PID in machines you know

  • Robot joints: *Modern Robotics* presents PID (Eq. 11.23) as a common joint feedback controller and even gives pseudocode for it (Figure 11.15).
  • 3D printers: Marlin holds hot-end and bed temperatures with PID (Lesson 6).
  • Everyday engineering: the *Control Tutorials* note that PID is widely employed because engineers understand it and it works well.
Two sous vide immersion circulators clipped into clear plastic water tubs in a kitchen, their displays showing set and actual temperatures, with eggs in one tub and vacuum-bagged meat in the other
Two sous vide circulators holding water baths at a set temperature — the displays show the set value and the measured value. Holding a water bath steady for hours is a classic feedback temperature-control job.Photo: Pedro.serna · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP
A home-built quadcopter with a wooden cross frame, four propellers and a red ball on top, standing on a tiled floor
A student quadcopter project. A multirotor cannot stay level without fast feedback from its motion sensors (Lesson 1) — the same feedback ideas, running on a tiny flight-controller board.Photo: Mais Jamal, Youshaa Murhij, Zain Alabide · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: full PID on the light keeper

The same LED + LDR circuit from Lessons 2–6, now with a small reusable PID struct: output limits 0–255, clamped integral, derivative on measurement and a fixed 100 Hz loop. Open the Serial Plotter and watch the three terms.

  1. Same wiring

    Pin 9 → 220 Ω → LED → GND; 5 V → LDR → A0 → 10 kΩ → GND; paper tube around both.

  2. Upload pid_light.ino

    Serial Plotter at 115200. You will see setpoint, reading, p_term, i_term, d_term and pwm.

  3. Disturb it

    Shade the sensor halfway, then remove the shade. Watch D react to the sudden change and I settle the long-term value.

  4. Turn terms off

    Set kd = 0, then ki = 0, then both. Note what each loses.

  5. Change the setpoint

    Try SETPOINT 400 and 750. Does the same PID work well at both? Why might it not?

pid_light.ino · Arduino C++
// pid_light.ino - a small, reusable PID "struct" running the LED + LDR light keeper.
// Wiring (same as Lessons 2-6): pin 9 -> 220 ohm -> LED -> GND;  5V -> LDR -> A0 -> 10k -> GND.
// Open Serial Plotter at 115200 to watch setpoint, reading and the P, I and D terms.

struct PID {
  float kp, ki, kd;
  float outMin, outMax;
  float integral;      // stored as I-term output (already multiplied by ki)
  float prevMeas;
  bool first;

  float update(float setpoint, float measured, float dt) {
    float error = setpoint - measured;
    float p = kp * error;
    integral += ki * error * dt;
    integral = constrain(integral, outMin, outMax);          // anti-windup clamp
    float dMeas = first ? 0 : (measured - prevMeas) / dt;   // derivative on measurement
    first = false;
    prevMeas = measured;
    float d = -kd * dMeas;
    lastP = p; lastD = d;
    return constrain(p + integral + d, outMin, outMax);
  }
  float lastP, lastD;
};

const int LED_PIN = 9, SENSOR_PIN = A0;
const int SETPOINT = 600;
const unsigned long PERIOD_MS = 10;          // 100 Hz loop
const float DT = PERIOD_MS / 1000.0;

// kp, ki, kd, outMin, outMax, integral, prevMeas, first
PID light = {0.2, 1.0, 0.002, 0, 255, 0, 0, true};
unsigned long lastTick = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  Serial.println(F("setpoint,reading,p_term,i_term,d_term,pwm"));
}

void loop() {
  if (millis() - lastTick < PERIOD_MS) return;   // fixed loop rate (Lesson 4)
  lastTick = millis();
  int reading = analogRead(SENSOR_PIN);
  int pwm = (int)light.update(SETPOINT, reading, DT);
  analogWrite(LED_PIN, pwm);

  Serial.print(SETPOINT); Serial.print(',');
  Serial.print(reading); Serial.print(',');
  Serial.print(light.lastP, 1); Serial.print(',');
  Serial.print(light.integral, 1); Serial.print(',');
  Serial.print(light.lastD, 1); Serial.print(',');
  Serial.println(pwm);
}

Debugging

Debugging a full PID

SymptomLikely causeFix
Oscillates and never settlesKp or Ki too highHalve Ki, then Kp; add a little Kd
Slow tail after a small overshootKi too high — integral stored during the riseLower Ki; clamp the integral
Buzzing or jittery outputKd amplifying noiseLower Kd; filter the derivative (Lesson 12)
Sign looks wrong — runs awayFeedback sign or wiring reversedCheck error = setpoint − measured and the sensor direction
Gains work at one setpoint but not anotherThe plant changes with operating point (e.g. LDR is non-linear)Tune at the working point; consider gain scheduling later
Changing loop speed changes everythingdt not used or not fixedFixed-rate loop; multiply I by dt and divide D by dt

Think

Think about it

Think

Priya’s robot arm uses PID on the shoulder. With no load it is perfect. When she adds a 200 g gripper, it still reaches the target, but it overshoots more and takes twice as long to settle. Which term is doing the extra work, and what could she change?

Experiment

Try it in the lab: build your own PID

About 35 minutes with the visualiser, the PID class and the light keeper.

Experiment

Build your own PID

You will need

  • PID visualiser (in your browser)
  • Your plots from Lessons 5–7
  • Optional: `pid_control.py`; Arduino UNO, LED, 220 Ω, LDR, 10 kΩ

Steps

  1. In the visualiser, compare P, PI, PD and PID on the same plant. Sketch all four on one graph.
  2. Run `pid_control.py`. Copy the mode table into your notebook.
  3. Using the order P → D → I, tune your own gains for a peak under 95° and settling under 1.5 s.
  4. Try your gains with `LOAD = 0.08`. Do they still meet the target?
  5. Optional bench: run `pid_light.ino`, disturb it, and switch terms off one by one.

Interactive · PID visualizer

PID terms cheat sheet: P speed, I removes SSE, D damps

Setpoint 70° · final θ 69.1° · |SSE| 0.94° · constant load on

Teaching model: Kp↑ snappier (overshoot risk); Ki↑ reduces steady-state error under load; Kd↑ damps the edge.

Each term fixes a different problem: P speed, I leftover error, D overshoot. Good PID gains balance all three for one plant and one operating point.

Knowledge check

Check your understanding

Knowledge check

1. The full PID law is…

2. In the code lab, which mode gave small overshoot AND almost no leftover error?

3. Why did PD stay 1.25° short?

4. At rest in the PID run, which term carries the gravity load?

5. During the fast rise, the D term is…

6. PID* (Ki = 0.01) settled slowly because…

7. The Control Tutorials’ suggested order for adding terms is…

8. Which is NOT part of a practical PID?

9. Do you always need all three terms?

10. Why print P, I and D separately while tuning?

Mini assignment

Hands-on assignment

Mini assignment

PID team report

Build, test and explain a full PID controller for the simulated joint (and optionally the light keeper).

Deliverables

  • Your own PID class (in Python or Arduino) with output limits, clamped integral and derivative on measurement.
  • A graph comparing P, PI, PD and PID for your gains.
  • A “who does the work” table for your PID, at five moments of a move.
  • Your final gains with one paragraph per term explaining its job.
  • If you built it: plotter screenshots of `pid_light.ino` during a shade test.

Do this, step by step

  1. Read pid_control.py, then run it and copy the P, PI, PD and PID comparison.
  2. Write your own PID class (Python or Arduino) with output limits, a clamped integral and derivative on measurement; test it on the same plant.
  3. Pick five moments of one move (start, rising, peak, settling, holding) and fill in a “who does the work” table with the P, I and D terms.
  4. In the PID visualiser switch between P, PI, PD and PID and find the mode with small overshoot and zero leftover error.
  5. If you have the light keeper: flash pid_light.ino, shade the LDR, then turn each term off in turn and save a plotter sketch of each. Write one paragraph per term on its job.

Stuck? Hints, one at a time

NoteTry the task first. Read one hint, try again, and only then read the next one.
  1. Hint 1: Start from pid_control.py; change only the gains in the mode list.
  2. Hint 2: If the tail is slow, look at the I column — is it overshooting 0.05?
  3. Hint 3: If the peak is too high, raise Kd before touching Kp.
  4. Hint 4: For the Arduino struct, remember first = true so the first derivative is zero.

Challenges (pick by level)

  • 🟢 Easy: Write the job of P, I and D in one line each, in your own words.
  • 🟢 Easy: From the inside table, at what time is the D term strongest?
  • 🟡 Medium: Add a step change in LOAD at t = 5 s and plot how each term reacts.
  • 🟡 Medium: Port the Python PID class to Arduino as a C++ class with a reset() method.
  • 🟠 Hard-ish: Add gravity feedforward (u += LOAD) and re-tune. How small can Ki become?
  • 🔴 Hard: Write an automatic search over Kp, Ki and Kd that minimises settling time with peak < 95°. Report the best gains and how long the search took.
  • ⚫ Research: Read Modern Robotics 11.4.1 and explain the practical limits it lists for PID on a real joint.

Next step

“Small overshoot, quick settling” needs numbers. In Lesson 9 — Step Response Metrics you learn to measure rise time, overshoot, settling time and steady-state error properly.

Look back: Lesson 7: Derivative Control (D). Next: Lesson 9: Step Response Metrics. Related: Stage 2 — Programming & Python (classes) and Stage 5 L08: Feedback & Closed-Loop Control.

Sources

Self-attested for now — keep artifacts in your lab notebook.

Complete

Today's goal

0 of 1 done today

0-day streak
Daily goal:lessons, quizzes or assignments a day

Mark this lesson complete when you have worked the experiment, knowledge check, and assignment (even roughly).

Watch on Quark Lab · GATE RA + PH

EP05: Feedback & PID Control

How does a robot joint hold still against gravity? The error e = r − y, proportional control and its steady-state error 1/(1 + Kp), integral action that removes the step offset (type-1 loop), derivative action as damping and why it needs a filter, the full PID law C(s) = Kp + Ki/s + Kd s, a side-by-side P vs PI vs PID step response, Ziegler–Nichols ultimate-gain tuning, a GATE-style solved problem and a numerical (NAT) question.

All Quark Lab episodes →

Stuck somewhere?

Ask a doubt about this lesson

Saved with this lesson's id and your email so we can reply. Privacy · or email contact@aihubstation.in