Stage 07 · Lesson 14/15

Control Systems & PID · Lesson 14

Practice: Response Lab Challenges

Est. 60–90 min

Why

Why practise on different joints

This is a practice lesson. There is no new theory — you use everything from Lessons 5–13: P, I and D (5–8), the step-response metrics (9), the tuning walk (10), saturation and anti-windup (11), filtering (12) and layered control (13). Each challenge has a different joint and a clear goal, and the code marks your answer PASS or try again.

By the end of this lesson you will be able to: tune PID gains to meet written goals on four different joints; explain why one set of gains does not fit every joint; use a derivative filter when the sensor is noisy; respect a torque limit while still meeting a goal; and run a self-marking step test on the LED + LDR bench.

A blue competition arena with marker posters on the walls and a raised square platform in the middle, at a student robotics event
The Student Robotics 2022 arena at the University of Southampton (photo description). Competitions give every team the same task and a clear score — just like the challenges in this lesson.Photo: Horshamwarrior · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

The four challenges

Four joints, four goals

ChallengeWhat makes it hardGoal
A — light wristVery little inertia: reacts fast, overshoots easilyOvershoot ≤ 5 %, settle ≤ 0.8 s, |SSE| ≤ 0.3°
B — heavy shoulder16× the inertia of A and a big gravity loadOvershoot ≤ 10 %, settle ≤ 2.5 s, |SSE| ≤ 0.3°
C — noisy sensor±0.3° random noise on every readingOvershoot ≤ 10 %, settle ≤ 2.0 s, |SSE| ≤ 0.5°, torque noise ≤ 0.3
D — weak motorTorque limit of only 0.3 — it saturatesOvershoot ≤ 5 %, settle ≤ 3.0 s, |SSE| ≤ 0.3°

Every challenge is a 90° step. Settling time uses the 2 % band, overshoot is measured against the final value, and SSE is the setpoint minus the final value — the same definitions as Lesson 9. Torque noise is how much the motor command jumps around while the joint should be still (half the peak-to-peak range in the last second).

Starting gains in challenges.py — none of them passes yet
ChallengeOvershootSettleSSETorque noiseResult
A light wrist7.2 %0.98 s0.50°0.00try again
B heavy shoulder16.0 %3.60 s4.98°0.01try again
C noisy sensor5.6 %1.38 s0.04°4.00try again
D weak motor1.6 %1.99 s0.66°0.00try again

Read the table like a doctor reads a report. A misses all three goals — it overshoots, settles too slowly and stops short (it needs more Kp and Kd, plus a little I). B has a big SSE because gravity pulls it down and there is no I term — and it is far too slow and bouncy for its weight. C meets the response goals, but the motor command shakes by ±4 because D amplifies the noise. D is close, but its I term cannot clear the last bit of error in time. All four have been checked: each one can be passed.

Visual

Visualise it: the response lab

Switch between a **clean**, a **loaded** and a **noisy** joint in the response lab. Keep the same gains and watch how differently each one responds.

Interactive · Control response lab

Goal: |SSE| ≤ 2°, overshoot ≤ 15% · Hint: Moderate Kp, light Kd, tiny Ki

|SSE|

0.24°

Overshoot

32.7%

Result

RETRY

Code lab

Code lab: the self-marking challenges

challenges.py simulates the four joints with a PID controller, conditional-integration anti-windup (Lesson 11) and an optional EMA filter on the derivative (Lesson 12). Edit the GAINS dictionary — (Kp, Ki, Kd, alpha) for each challenge — and run python3 challenges.py. alpha = 1.0 means no filtering; a smaller alpha filters more.

challenges.py · Python
# challenges.py - four tuning challenges on four different "joints". Edit the GAINS and run.
# Each challenge has its own plant and its own goal. The checker uses the Lesson 9 metrics.
import random

DT, T_END, SETPOINT = 0.001, 6.0, 90.0

CHALLENGES = {
    # name: (inertia J, damping B, gravity LOAD, torque limit, sensor noise deg, goal)
    "A light wrist":   (0.0005, 0.002, 0.01, 1.0, 0.0, dict(overshoot=5, settle=0.8, sse=0.3)),
    "B heavy shoulder": (0.008, 0.01, 0.20, 4.0, 0.0, dict(overshoot=10, settle=2.5, sse=0.3)),
    "C noisy sensor":  (0.002, 0.004, 0.05, 4.0, 0.3, dict(overshoot=10, settle=2.0, sse=0.5, torque_noise=0.3)),
    "D weak motor":    (0.002, 0.004, 0.05, 0.3, 0.0, dict(overshoot=5, settle=3.0, sse=0.3)),
}

# ---- YOUR GAINS: (Kp, Ki, Kd, derivative EMA alpha) -- start from these and improve ----
GAINS = {
    "A light wrist":    (0.02, 0.0, 0.002, 1.0),
    "B heavy shoulder": (0.04, 0.0, 0.008, 1.0),
    "C noisy sensor":   (0.04, 0.002, 0.008, 1.0),
    "D weak motor":     (0.04, 0.004, 0.008, 1.0),
}


def run(plant, gains):
    J, B, LOAD, TMAX, NOISE, _ = plant
    kp, ki, kd, alpha = gains
    r = random.Random(3)
    angle = speed = integral = d_filt = 0.0
    prev = 0.0
    ys, hold_tau = [], []
    for i in range(int(T_END / DT)):
        m = angle + r.uniform(-NOISE, NOISE)
        e = SETPOINT - m
        d_filt = alpha * (m - prev) / DT + (1 - alpha) * d_filt
        prev = m
        raw = kp * e + ki * integral - kd * d_filt
        tau = max(-TMAX, min(TMAX, raw))
        if tau == raw and ki > 0:                       # conditional integration (Lesson 11)
            integral += e * DT
        speed += (tau - B * speed - LOAD) / J * DT
        angle += speed * DT
        ys.append(angle)
        if i * DT > T_END - 1.0:
            hold_tau.append(tau)
    final = sum(ys[-200:]) / 200
    overshoot = max(0.0, (max(ys) - final) / final * 100)
    settle = 0.0
    for i, y in enumerate(ys):
        if abs(y - final) > abs(final) * 0.02:
            settle = (i + 1) * DT
    tn = (max(hold_tau) - min(hold_tau)) / 2
    return overshoot, settle, SETPOINT - final, tn


print(f"{'challenge':<17} {'gains (Kp,Ki,Kd,alpha)':<26} {'overshoot':>9} {'settle':>7} {'SSE':>7} {'tq noise':>8}  result")
for name, plant in CHALLENGES.items():
    os_, st, sse, tn = run(plant, GAINS[name])
    g = plant[5]
    ok = os_ <= g["overshoot"] and st <= g["settle"] and abs(sse) <= g["sse"] and tn <= g.get("torque_noise", 99)
    print(f"{name:<17} {str(GAINS[name]):<26} {os_:>8.1f}% {st:>6.2f}s {sse:>6.2f}° {tn:>8.2f}  {'PASS' if ok else 'try again'}")
print("\nGoals: A os<=5% settle<=0.8s | B os<=10% settle<=2.5s | C os<=10% settle<=2.0s torque noise<=0.3")
print("       D os<=5% settle<=3.0s | all: |SSE| <= 0.3 deg (C: 0.5)")

Output with the starting gains (run with python3 challenges.py)

challenge         gains (Kp,Ki,Kd,alpha)     overshoot  settle     SSE tq noise  result
A light wrist     (0.02, 0.0, 0.002, 1.0)         7.2%   0.98s   0.50°     0.00  try again
B heavy shoulder  (0.04, 0.0, 0.008, 1.0)        16.0%   3.60s   4.98°     0.01  try again
C noisy sensor    (0.04, 0.002, 0.008, 1.0)       5.6%   1.38s   0.04°     4.00  try again
D weak motor      (0.04, 0.004, 0.008, 1.0)       1.6%   1.99s   0.66°     0.00  try again

Goals: A os<=5% settle<=0.8s | B os<=10% settle<=2.5s | C os<=10% settle<=2.0s torque noise<=0.3
       D os<=5% settle<=3.0s | all: |SSE| <= 0.3 deg (C: 0.5)

Warm up here: tune the gains and watch overshoot and settling time change before you edit the code.

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.

Real world

Tuning challenges in the real world

  • Robotics competitions: every team gets the same task and the same scoring rules.
  • Schools and clubs: mentors help students test, fix and test again before their turn.
  • Engineering teams: a controller is accepted when it meets written goals — not when it ‘looks fine’.
Two school students adjusting their small robot at a competition table while an adult mentor and a referee in a striped shirt watch
Junior high school students make last-minute adjustments at a FIRST robotics qualifying tournament in O’Fallon, Illinois, in 2014 (photo description). Test, adjust, test again — the same loop you use in this lesson.Photo: Staff Sgt. Stephenie Wade (U.S. Air Force) · Public domain · Source: Wikimedia Commons · resized, converted to WebP
A large group of students in matching school uniforms standing behind a row of metal VEX competition robots
Students of the School of Science and Technology, Singapore, with their robots at the Singapore VEX Robotics Championship 2010 (photo description).Photo: Wrc Ynapmoc. · CC BY 3.0 · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: a self-marking light keeper

Back to the LED + LDR light keeper from Lessons 2–12. challenge_checker.ino steps the setpoint between 450 and 700 every 6 seconds, measures overshoot, settling time (2 % of the step) and SSE (from the average of the last second), and prints PASS or TRY AGAIN for each step.

  1. Wire the light keeper

    Pin 9 → 220 Ω resistor → LED → GND. 5 V → LDR → A0, and A0 → 10 kΩ → GND. Point the LED at the LDR and cover both with a small paper tube to keep out room light.

  2. Upload and open Serial Monitor

    Set 115200 baud. Wait for a few # step to … lines.

  3. Read the report

    Which goal fails — overshoot, settle or SSE? Use the table in the code lab tips to decide which gain to change.

  4. Tune and re-upload

    Change one of KP, KI, KD, re-upload, and watch the next few steps. Stop when both the up step and the down step pass.

  5. Change the plant

    Move the LED a little further away (a ‘weaker motor’) and test again. Do your gains still pass?

challenge_checker.ino · Arduino C++
// challenge_checker.ino - a self-marking tuning challenge on the LED + LDR light keeper.
// Wiring (same as Lessons 2-12): pin 9 -> 220 ohm -> LED -> GND;  5V -> LDR -> A0 -> 10k -> GND.
// Every 6 s the setpoint steps between LOW_SP and HIGH_SP. The board measures overshoot,
// settling time (2 %) and steady-state error for each step and prints PASS or TRY AGAIN.
// Tune KP, KI, KD (or use tune_serial.ino from Lesson 10 first), re-upload, and try to pass.

const int LED_PIN = 9, SENSOR_PIN = A0;
const int LOW_SP = 450, HIGH_SP = 700;
float KP = 0.2, KI = 1.0, KD = 0.002;
const float GOAL_OVERSHOOT = 5.0;      // %
const float GOAL_SETTLE_MS = 600;      // ms
const float GOAL_SSE = 10;             // ADC counts
const unsigned long PERIOD_MS = 5, STEP_MS = 6000;
const float DT = PERIOD_MS / 1000.0;

float integral = 0, prevReading = 0;
int setpoint = LOW_SP, startVal = 0;
unsigned long stepStart = 0, lastTick = 0, lastOutside = 0;
int peak = 0, trough = 1023;
long sumLast = 0; int nLast = 0;

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  Serial.println(F("Self-marking challenge: overshoot<5%, settle<600 ms, |SSE|<10 counts"));
}

void report() {
  float finalV = nLast ? (float)sumLast / nLast : 0;
  float span = finalV - startVal;
  bool up = span > 0;
  float over = span != 0 ? ((up ? peak - finalV : finalV - trough) / fabs(span)) * 100 : 0;
  if (over < 0) over = 0;
  float settle = lastOutside - stepStart;
  float sse = setpoint - finalV;
  bool pass = over <= GOAL_OVERSHOOT && settle <= GOAL_SETTLE_MS && fabs(sse) <= GOAL_SSE;
  Serial.print(F("# step to ")); Serial.print(setpoint);
  Serial.print(F(": overshoot=")); Serial.print(over, 1);
  Serial.print(F("% settle=")); Serial.print(settle, 0);
  Serial.print(F("ms SSE=")); Serial.print(sse, 1);
  Serial.println(pass ? F("  PASS") : F("  TRY AGAIN"));
}

void loop() {
  if (millis() - lastTick < PERIOD_MS) return;
  lastTick = millis();
  int reading = analogRead(SENSOR_PIN);

  if (millis() - stepStart >= STEP_MS) {           // end of a step: mark it, start the next
    if (stepStart != 0) report();
    setpoint = (setpoint == LOW_SP) ? HIGH_SP : LOW_SP;
    stepStart = millis(); lastOutside = stepStart;
    startVal = reading; peak = reading; trough = reading; sumLast = 0; nLast = 0;
  }

  float error = setpoint - reading;
  integral = constrain(integral + KI * error * DT, 0, 255);
  float d = -KD * (reading - prevReading) / DT;
  prevReading = reading;
  analogWrite(LED_PIN, constrain((int)(KP * error + integral + d), 0, 255));

  peak = max(peak, reading); trough = min(trough, reading);
  if (abs(reading - setpoint) > 0.02 * abs(setpoint - startVal)) lastOutside = millis();
  if (millis() - stepStart > STEP_MS - 1000) { sumLast += reading; nLast++; }   // last 1 s = final value
}

Debugging

Debugging your tuning

Report saysLikely causeTry
Overshoot too highToo much Kp or Ki, too little KdRaise Kd, or lower Ki
Settle too slow, no overshootToo little gainRaise Kp, then add Kd
SSE too bigGravity load or friction, no IAdd a small Ki
Motor command shakingDerivative of a noisy sensorLower alpha (filter) or Kd
Up step passes, down step failsThe light keeper does not respond the same way going up and downTune for the harder direction
Result changes every runRoom light leaking inCover the LED and LDR with a paper tube

Think

Think about it

Think

Ritika wants to stop the shaking in challenge C, so she sets Kd = 0. The torque noise drops from 4.00 to 0.03. “Done!” she says. Is she?

Experiment

Try it in the lab: beat all four challenges

About 45 minutes with challenges.py, the tuning lab and (optionally) the light keeper bench.

Experiment

Beat all four challenges

You will need

  • PID tuning lab and response lab (in your browser)
  • `challenges.py`
  • Optional: Arduino UNO, LED, 220 Ω resistor, LDR, 10 kΩ resistor, jumper wires, small paper tube

Steps

  1. Run `challenges.py` with the starting gains and copy the table into your notebook.
  2. For each challenge, write which goal fails and which gain you will change first.
  3. Tune A, then D, then B, then C. Record every try in your tuning log.
  4. When all four pass, change each passing gain by +20 % and run again. Which challenge breaks first?
  5. Optional bench: get both steps of `challenge_checker.ino` to PASS, then move the LED and test again.

Interactive · Control response lab

Goal: |SSE| ≤ 2°, overshoot ≤ 15% · Hint: Moderate Kp, light Kd, tiny Ki

|SSE|

0.24°

Overshoot

32.7%

Result

RETRY

Each joint needs its own gains. The heavy, loaded joint needs much bigger gains and an I term; the noisy one needs a filter; the weak one needs patience, because no gain can beat a torque limit.

Knowledge check

Check your understanding

Knowledge check

1. Challenge B (heavy shoulder) has a big steady-state error with the starting gains. The best first fix is…

2. In challenge C, the motor command shakes by about ±4 with the starting gains. The cause is…

3. In challenges.py, alpha = 1.0 means…

4. Challenge D has a torque limit of 0.3. Raising Kp a lot will…

5. Settling time in these challenges uses…

6. Why can’t the light wrist’s gains be copied to the heavy shoulder?

7. On the light keeper bench, room light changes your results each run. The fix is…

8. After all four challenges pass, a good next test is…

Mini assignment

Hands-on assignment

Mini assignment

Response lab challenge report

Pass all four challenges and show how you got there.

Deliverables

  • Your final `GAINS` for all four challenges and the PASS output of `challenges.py`.
  • Your tuning log: every set of gains you tried, with its result.
  • One paragraph per challenge: what made it hard and which gain fixed it.
  • The +20 % margin test: which challenge broke first, and why you think so.
  • If you built it: the PASS lines from `challenge_checker.ino` and a photo of your bench.

Do this, step by step

  1. Run python3 challenges.py once with the starting GAINS and note which of the four challenges fail and why.
  2. Tune one challenge at a time: change one gain, run, and log the gains and result every time.
  3. When all four PASS, copy the final GAINS and the PASS output.
  4. Run the +20% margin test and note which challenge breaks first; explain why in one sentence.
  5. If you have the light keeper: flash challenge_checker.ino, tune until the PASS lines appear, then write one paragraph per challenge on what made it hard.

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: A needs more Kp *and* more Kd together, plus a little Ki for the SSE.
  2. Hint 2: For D, a bigger Ki helps clear the last error — conditional integration stops it winding up while the motor is saturated.
  3. Hint 3: For C, keep your gains and try alpha = 0.1, then 0.03. Check the overshoot each time.
  4. Hint 4: B needs much bigger gains than the others. One set that passes is Kp 0.16, Ki 0.01, Kd 0.06 — try to find a faster one.

Challenges (pick by level)

  • 🟢 Easy: Pass challenge A.
  • 🟢 Easy: Pass challenge D.
  • 🟡 Medium: Pass all four challenges.
  • 🟡 Medium: Get both steps of challenge_checker.ino to PASS on your bench.
  • 🟠 Hard-ish: Find one set of gains that passes both A and D. If you can’t, explain why.
  • 🔴 Hard: Add a fifth challenge to challenges.py — a joint whose gravity load is LOAD × cos θ — set fair goals and pass it.
  • ⚫ Research: Write a small automatic tuner that searches the gains for challenge B and prints the fastest PASS. Compare it with your hand tuning.

Next step

You have practised on four joints. In Lesson 15 — Capstone: Tune a Robot Joint you bring everything together on one robot joint and write a full tuning report.

Look back: Lesson 13: Robot Joint Control Architecture. Next: Lesson 15: Capstone: Tune a Robot Joint. Related: Stage 12 — Simulation & Digital Twin (practise in simulation).

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