Stage 07 · Lesson 10/15

Control Systems & PID · Lesson 10

Tuning Intuition

Est. 60–75 min

Why

Why tuning is a method, not luck

You now know what P, I and D do (Lessons 5–8) and how to measure a response (Lesson 9). Tuning is putting those together: choose a goal in numbers, change one gain at a time, measure, and repeat. The Michigan *Control Tutorials* give a simple order: look at the response first, then add P to improve rise time, D to reduce overshoot, and I to reduce steady-state error, and adjust until the overall response is right.

By the end of this lesson you will be able to: write a tuning goal in numbers; follow the P → D → I walk on the simulated joint; recognise each gain’s fingerprint on a response; tune the LED + LDR loop live over Serial; and keep a tuning log that another person could repeat.

Close-up of the carved wooden tuning pegs of a Saraswati veena
The tuning pegs (kunti) of a Saraswati veena. Musicians turn one peg at a time and listen after each turn — exactly the habit a good PID tuner needs.Photo: Pp391 · CC BY-SA 3.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

A simple, repeatable tuning walk

Step 0: write the goal in numbers

“Make it good” is not a goal. For the joint in this lesson we use: overshoot under 10 %, settling time (2 %) under 1.5 s, and steady-state error smaller than 0.2°. A camera arm might want zero overshoot; a pick-and-place arm might care most about settling. Choose for your task.

The walk

Results from tuning_walk.py (same joint as Lessons 5–9)
StepKpKiKdOvershootSettlingSSEGoal?
1. P only, small0.005007.7 %3.79 s10.00°—
1. double Kp0.010020.8 %3.73 s5.00°—
1. double again0.020035.1 %3.53 s2.50°—
1. double again0.040048.6 %3.78 s1.25°—
2. add D0.0400.00420.7 %1.86 s1.25°—
2. double Kd0.0400.0085.8 %1.34 s1.25°—
3. add a little I0.040.0010.0085.7 %1.33 s0.45°—
3. double Ki0.040.0020.0085.9 %1.35 s−0.07°PASS
3. double Ki again0.040.0040.0086.9 %1.46 s−0.57°—
4. Ki 0.002, trim Kd0.040.0020.0102.0 %0.82 s−0.21°just misses

Watch the story. Doubling Kp cuts the leftover error in half each time — and piles on overshoot. Adding D pulls the overshoot down to 5.8 % and settling to 1.34 s. A little I removes the leftover error; too much I makes it worse again. The last row is interesting: more Kd gives a faster, calmer response, but the SSE at 10 s just misses the goal because the integral is still finishing its work. Tuning is full of trade-offs like this — your numbers tell you which way to lean.

Each gain’s fingerprint

You see…Most likelyTry
Slow rise, big leftover errorKp too smallDouble Kp
Fast rise, big overshoot, ringingKp high, Kd too smallRaise Kd
Calm, but stops short of the targetNo (or too little) IAdd a small Ki
Slow, rolling overshoot and long tailKi too bigHalve Ki
Buzzing, jittery outputKd too big for the sensor noiseLower Kd, filter (Lesson 12)
Very slow creep to the targetKd too big (over-damped)Lower Kd
A machine-workshop control panel with a red emergency-stop button, rotary knobs and rows of buttons
A machine control panel with knobs — and a big red emergency stop. When you tune a real machine, keep the stop within reach and start with gentle gains.Photo: Shixart1985 · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Visual

Visualise it: tune the joint yourself

Tune the joint yourself: **P first, then D, then I**. Change one gain at a time and compare the response with your numeric goal.

Interactive · PID tuning lab

Rise time

1.60s

Overshoot

20.5%

|SSE|

2.02°

Settled?

Yes

Recipe: raise Kp until lively but not wild → add Kd to calm overshoot → add Ki to kill SSE under load → back off if it rings.

Code lab

Code lab: an automatic tuning log

tuning_walk.py runs the walk above, measures each step with the Lesson 9 metrics, and marks the steps that meet the goal. It is a tuning log you can rerun at any time. Run it with python3 tuning_walk.py.

tuning_walk.py · Python
# tuning_walk.py - a step-by-step manual PID tuning walk on the same joint as Lessons 5-9.
# Order (Michigan Control Tutorials tips): P for rise time -> D for overshoot -> I for steady-state error.
# Goal: overshoot < 10 %, settling (2 %) < 1.5 s, |SSE| < 0.2 deg.

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


def simulate(kp, ki, kd):
    angle = speed = integral = t = 0.0
    prev = angle
    ys = []
    while t < T_END:
        e = SETPOINT - angle
        if ki > 0:
            integral = max(-TAU_MAX / ki, min(TAU_MAX / ki, integral + e * DT))
        d_meas = (angle - prev) / DT
        prev = angle
        torque = max(-TAU_MAX, min(TAU_MAX, kp * e + ki * integral - kd * d_meas))
        speed += (torque - B * speed - LOAD) / J * DT
        angle += speed * DT
        t += DT
        ys.append(angle)
    return ys


def metrics(ys):
    final = sum(ys[-200:]) / 200
    peak = max(ys)
    overshoot = max(0.0, (peak - final) / final * 100)
    band = abs(final) * 0.02
    settle = 0.0
    for i, y in enumerate(ys):
        if abs(y - final) > band:
            settle = (i + 1) * DT
    return overshoot, settle, SETPOINT - final


def ok(os_, st, sse):
    return "PASS" if os_ < 10 and st < 1.5 and abs(sse) < 0.2 else "-"


steps = [
    ("1. P only, small", 0.005, 0, 0),
    ("1. P only, double", 0.01, 0, 0),
    ("1. P only, double again", 0.02, 0, 0),
    ("1. P only, double again", 0.04, 0, 0),
    ("2. add D", 0.04, 0, 0.004),
    ("2. double D", 0.04, 0, 0.008),
    ("3. add a little I", 0.04, 0.001, 0.008),
    ("3. double I", 0.04, 0.002, 0.008),
    ("3. double I again", 0.04, 0.004, 0.008),
    ("4. back to Ki=0.002, trim Kd", 0.04, 0.002, 0.010),
]
print(f"{'step':<30} {'Kp':>6} {'Ki':>6} {'Kd':>6} {'overshoot':>9} {'settle':>7} {'SSE':>7}  goal")
for name, kp, ki, kd in steps:
    os_, st, sse = metrics(simulate(kp, ki, kd))
    print(f"{name:<30} {kp:>6} {ki:>6} {kd:>6} {os_:>8.1f}% {st:>6.2f}s {sse:>6.2f}°  {ok(os_, st, sse)}")
print("\nChange ONE gain at a time, by a factor of about 2, and measure after every change.")

Output (run with python3 tuning_walk.py)

step                               Kp     Ki     Kd overshoot  settle     SSE  goal
1. P only, small                0.005      0      0      7.7%   3.79s  10.00°  -
1. P only, double                0.01      0      0     20.8%   3.73s   5.00°  -
1. P only, double again          0.02      0      0     35.1%   3.53s   2.50°  -
1. P only, double again          0.04      0      0     48.6%   3.78s   1.25°  -
2. add D                         0.04      0  0.004     20.7%   1.86s   1.25°  -
2. double D                      0.04      0  0.008      5.8%   1.34s   1.25°  -
3. add a little I                0.04  0.001  0.008      5.7%   1.33s   0.45°  -
3. double I                      0.04  0.002  0.008      5.9%   1.35s  -0.07°  PASS
3. double I again                0.04  0.004  0.008      6.9%   1.46s  -0.57°  -
4. back to Ki=0.002, trim Kd     0.04  0.002   0.01      2.0%   0.82s  -0.21°  -

Change ONE gain at a time, by a factor of about 2, and measure after every change.

Try it: follow the walk — P first, then D, then I. Change one slider at a time and watch the response after every change.

Interactive · PID tuning lab

Rise time

1.60s

Overshoot

20.5%

|SSE|

2.02°

Settled?

Yes

Recipe: raise Kp until lively but not wild → add Kd to calm overshoot → add Ki to kill SSE under load → back off if it rings.

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

Tuning in the real world

  • 3D printers: Marlin’s M303 autotune heats and cools the hot end to find PID values automatically (Lesson 6).
  • MATLAB: the Control Tutorials show pidTuner, which picks gains to balance speed and robustness.
  • Your arm project: the shoulder carries more weight than the wrist, so check each joint’s tuning with its real load.
  • Musicians and mechanics: small, single changes and careful listening — the same habit.
Three rotary knobs on a hotel ventilation and climate control unit
Climate-control knobs on a hotel ventilation system. Knobs like these only set the *target*; a feedback loop does the rest — and that loop works well only if someone tuned it at the real operating point.Photo: Derek Jensen (Tysto) · Public domain · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: live tuning over Serial

tune_serial.ino runs the LED + LDR loop and lets you change Kp, Ki, Kd and the setpoint by typing commands — no re-uploading. Watch the Serial Plotter as you tune.

  1. Same wiring

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

  2. Start with P only

    Open the Serial Monitor (115200, Newline). Type p 0.1, then s 700, then s 500. Note how close the reading gets.

  3. Double Kp

    p 0.2, p 0.4 … repeat the setpoint steps each time. Stop when it starts to wobble; go back one step.

  4. Add D, then I

    Try d 0.001, d 0.002. Then i 0.5, i 1.0. Log every change and the result.

  5. Disturb it

    Shade the sensor halfway. Does your final tuning recover well?

tune_serial.ino · Arduino C++
// tune_serial.ino - tune the LED + LDR light keeper live from the Serial Monitor.
// Wiring (same as Lessons 2-9): pin 9 -> 220 ohm -> LED -> GND;  5V -> LDR -> A0 -> 10k -> GND.
// Commands (Serial Monitor at 115200, "Newline" line ending):
//   p 0.3    set Kp        i 1.0   set Ki        d 0.002   set Kd
//   s 700    set setpoint  g       print gains   r         reset the integral
// Change ONE gain at a time, then shade/unshade the sensor or change the setpoint and watch.

const int LED_PIN = 9, SENSOR_PIN = A0;
const unsigned long PERIOD_MS = 10;
const float DT = PERIOD_MS / 1000.0;

float kp = 0.1, ki = 0.0, kd = 0.0;
int setpoint = 600;
float integral = 0, prevReading = 0;
unsigned long lastTick = 0;

void printGains() {
  Serial.print(F("# Kp=")); Serial.print(kp, 4);
  Serial.print(F(" Ki=")); Serial.print(ki, 4);
  Serial.print(F(" Kd=")); Serial.print(kd, 4);
  Serial.print(F(" setpoint=")); Serial.println(setpoint);
}

void handleSerial() {
  if (!Serial.available()) return;
  char cmd = Serial.read();
  float value = Serial.parseFloat();
  while (Serial.available()) Serial.read();
  switch (cmd) {
    case 'p': kp = max(0.0f, value); break;
    case 'i': ki = max(0.0f, value); break;
    case 'd': kd = max(0.0f, value); break;
    case 's': setpoint = constrain((int)value, 50, 1000); break;
    case 'r': integral = 0; break;
    default: break;
  }
  printGains();
}

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  printGains();
}

void loop() {
  handleSerial();
  if (millis() - lastTick < PERIOD_MS) return;
  lastTick = millis();

  int reading = analogRead(SENSOR_PIN);
  float error = setpoint - reading;
  integral = constrain(integral + ki * error * DT, 0, 255);     // clamped I term
  float d = -kd * (reading - prevReading) / DT;                  // derivative on measurement
  prevReading = reading;
  int pwm = constrain((int)(kp * error + integral + d), 0, 255);
  analogWrite(LED_PIN, pwm);

  static int n = 0;
  if (++n % 5 == 0) {            // print every 50 ms for the Serial Plotter
    Serial.print(setpoint); Serial.print(',');
    Serial.print(reading); Serial.print(',');
    Serial.println(pwm);
  }
}

Debugging

Debugging a tuning session

SymptomLikely causeFix
Every change seems to make it worseChanging several gains at onceGo back to the last good log entry; change one gain
Results differ each runNoise, room light, warm-upRepeat each test 3 times; same conditions
Great in the lab, bad on the robotDifferent load or operating pointTune with the real load
Serial command does nothingWrong line ending or baud rate115200 baud, “Newline” ending
Gains good, output stuck at 255Setpoint unreachableLower the setpoint; check the LED is aimed at the LDR

Think

Think about it

Think

Kabir’s arm passes the tuning goal with no load. With a 300 g object in the gripper, the overshoot jumps to 18 %. His friend says “just raise Kd until it passes again”. What else should he check before changing gains?

Experiment

Try it in the lab: tune to a goal

About 35 minutes with the tuning lab, the tuning walk and the live Serial tuner.

Experiment

Tune to a goal

You will need

  • PID tuning lab (in your browser)
  • `tuning_walk.py`
  • Optional: Arduino UNO, LED, 220 Ω, LDR, 10 kΩ

Steps

  1. Write your goal in numbers (overshoot, settling, SSE).
  2. In the tuning lab, follow P → D → I, one change at a time. Log every change.
  3. Run `tuning_walk.py` and compare its path with yours.
  4. Change the goal (e.g. overshoot < 3 %) and tune again.
  5. Optional bench: tune `tune_serial.ino` live and keep a written log.

Interactive · PID tuning lab

Rise time

1.60s

Overshoot

20.5%

|SSE|

2.02°

Settled?

Yes

Recipe: raise Kp until lively but not wild → add Kd to calm overshoot → add Ki to kill SSE under load → back off if it rings.

A clear goal plus one-change-at-a-time turns tuning from guessing into a method. Your log is the proof.

Knowledge check

Check your understanding

Knowledge check

1. The first step in tuning is…

2. The Control Tutorials’ suggested order is…

3. In the walk, doubling Kp each time…

4. Which step first passed the goal?

5. “Slow, rolling overshoot with a long tail” most likely means…

6. Why change one gain at a time?

7. Why use factors of about 2 at the start?

8. If PD already passes your goal, you should…

9. Gains tuned with no load may fail with a load because…

10. What does `tune_serial.ino` let you do?

Mini assignment

Hands-on assignment

Mini assignment

Tuning log

Tune a loop to a written goal and keep a log that someone else could follow.

Deliverables

  • Your goal in numbers, with one sentence on why it suits the task.
  • A tuning log (at least 8 entries): gains, metrics, PASS/FAIL, one-line note.
  • Plots of the first, a middle, and the final response.
  • If you built it: your live Serial tuning log for the light keeper.
  • A short “fingerprint card” — symptoms and which gain to change.

Do this, step by step

  1. Write your goal in numbers (for example overshoot < 10%, settling < 2 s, error < 0.5°) and one sentence on why it suits the task.
  2. Run python3 tuning_walk.py, read the log, and mark which gain each step changed.
  3. Start your own log: P only first, then double Kp until it oscillates, back off, add D, then a little I — one change per entry, at least 8 entries with PASS/FAIL.
  4. Use the PID tuning lab widget to rehearse the same walk and save the first, a middle and the final response.
  5. If you have the light keeper: flash tune_serial.ino, change gains live over Serial, and log every try. Finish with a fingerprint card (symptom → gain to change).

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 with P only and double it until the response starts to ring.
  2. Hint 2: Add D in small steps until the ringing is gone.
  3. Hint 3: Add the smallest Ki that removes the leftover error within your time budget.
  4. Hint 4: If two settings both pass, choose the one with the smaller gains — it is usually gentler on hardware.

Challenges (pick by level)

  • 🟢 Easy: Fill in the fingerprint table from memory.
  • 🟢 Easy: Choose a goal for a camera gimbal and explain it.
  • 🟡 Medium: Make tuning_walk.py stop automatically at the first PASS.
  • 🟡 Medium: Tune the bench loop at two setpoints (400 and 750). Are the best gains the same?
  • 🟠 Hard-ish: Write a simple automatic tuner: start with P only, double Kp until overshoot > 30 %, then add D until overshoot < 10 %, then add I.
  • 🔴 Hard: Make your automatic tuner robust to noise (repeat each test and average).
  • ⚫ Research: Read about MATLAB pidTuner in the Control Tutorials and explain what “robustness” means in that context.

Next step

Real actuators have limits. In Lesson 11 — Saturation, Windup & Safety Limits you learn what happens when the controller asks for more than the motor can give — and how to keep the loop (and you) safe.

Look back: Lesson 9: Step Response Metrics. Next: Lesson 11: Saturation, Windup & Safety Limits. Related: Stage 12 — Simulation & Digital Twin (tune in simulation first).

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).

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