Stage 07 · Lesson 04/15

Control Systems & PID · Lesson 04

Control Loop Anatomy

Est. 55–70 min

Why

Why you must be able to name every block

So far you have used words like setpoint, error and controller. Now we put the whole loop on the table, block by block, the way control engineers draw it. Once you can name each block and the signal on each arrow, debugging becomes a hunt along a chain instead of guesswork: “Is the sensor right? Is the error right? Is the command right? Did the actuator obey? Did the plant respond?”

By the end of this lesson you will be able to: draw a feedback loop with reference, comparator, controller, actuator, plant, sensor and disturbance; name the signal on each arrow (r, e, u, y); explain inner and outer loops in a robot joint; write a fixed-rate control loop in Arduino code; and show with a simulation why a slow loop rate causes overshoot even with the same gain.

A black-and-white block diagram: input R(s) enters a summing circle, goes through block G(s) to output Y(s), and a feedback path through block H(s) returns to the summing circle with a minus sign
The standard closed-loop block diagram. The reference R enters a summing junction (the comparator), the controller-and-plant block G produces the output Y, and the feedback path H (the sensor) brings Y back with a minus sign so the junction computes the error. Engineers draw almost every loop this way.Photo: Duongdatninja146 · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Concept

The blocks of a feedback loop, one by one

Think of a pressure cooker on the stove. You want the right pressure (the reference). The weight on the vent effectively compares the pressure with its setting (comparator and controller in one). The flame and vessel are the actuator and plant. The whistle tells you what is happening (a crude sensor for you). And opening a window, a gust of wind on the flame or adding cold water are disturbances. Every loop has the same parts — only the materials change.

The seven blocks and four signals

Anatomy of a robot-joint position loop
Block / signalSymbolJobRobot-joint example
Reference (setpoint)rWhat you wantDesired angle 60° from the trajectory planner
Comparator (summing junction)e = r − ySubtracts measurement from referenceOne line of code: error = ref - measured
Controlleru = f(e)Turns error into a commandP, PI or PID in the microcontroller
Actuator—Turns the command into force or motionMotor driver + motor + gearbox
Plant—The thing being controlledThe arm link and its load
Sensor (feedback path)yMeasures the outputEncoder or potentiometer
DisturbancedAnything that pushes the plant off courseGravity, friction, a bump

The Michigan *Control Tutorials* describe exactly this “unity-feedback” loop: the error e — the difference between desired and actual output — is fed to the controller; the controller’s signal u goes to the plant; the new output y is fed back and compared with the reference to find a new error; and the process continues while the controller is running.

A blue block diagram: input I enters a summing junction, then an amplifier block A, then a second summing junction where a disturbance D is added, giving output O; a feedback block beta returns O to the first junction
Where disturbances enter. In this classic feedback diagram, a disturbance D is added *after* the forward block. Because the feedback path measures the output including D, the loop sees the disturbance and works against it — that is why feedback rejects disturbances that open loop cannot.Photo: Brews ohare · CC0 · Source: Wikimedia Commons · resized, converted to WebP

Inner and outer loops

*Modern Robotics* (Figure 11.1) points out that a typical robot control system has more than one loop. The outer loop controls position. Inside it, the motor amplifier often runs its own inner loop — for example, a DC motor amplifier in torque mode senses the current actually flowing through the motor and corrects it, because motor current is proportional to torque. The outer loop says “I need this much torque”; the inner loop makes sure the motor really delivers it. The book also notes that disturbance forces can be injected before or after the arm’s dynamics.

Nested loops in a typical robot joint (fastest inside)
LoopMeasuresCommandsTypical job
Outer: positionJoint angle (encoder)Speed or torqueReach 60° and hold it
Middle: speed (sometimes)Joint speedTorque / currentMove smoothly at the planned speed
Inner: currentMotor currentVoltage (PWM)Deliver the requested torque

Loop rate: how often the message goes round

A controller only sees the world when it samples the sensor. Between samples it is blind and keeps sending the old command. If the loop runs too slowly, the plant moves a long way on a stale command — just like the bucket chain overfilling the tank. The code lab shows it with numbers: the same gain gives no overshoot at 100 Hz, about 1° at 20 Hz and over 6° at 5 Hz. In code, that means: run the loop at a fixed rate using millis() or micros(), and keep slow things like Serial.print out of every tick.

loop period T = 1 ÷ loop rate e.g. 100 Hz → T = 10 ms

  • The loop must run fast compared with how quickly the plant moves. In the code lab, a joint that settles in well under a second behaves well at 100 Hz and poorly at 5 Hz. Current loops need far faster rates and normally live inside the motor driver.
A blue Arduino UNO-compatible board, a red CNC shield carrying purple stepper driver modules, and a square black NEMA 17 stepper motor, laid side by side on a white surface
Controller, driver and actuator on one bench. An Arduino-compatible board (controller), a CNC shield carrying stepper driver modules (the power stage of the actuator) and a NEMA 17 stepper motor. Add a sensor and a feedback path and you have every block of the loop on your desk.Photo: DotEagle · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Visual

Visualise it: trace the signal around the loop

Follow the signal around the loop: **reference → comparator → controller → actuator → plant → sensor → back to the comparator**. Add a disturbance and watch where it enters and how the loop answers.

Interactive · Control loop explorer

Closed-loop control block diagram: setpoint, error, PID, plant, feedback

Mode

Closed

θ final

61.6°

Error

-1.6°

Closed-loop uses error = setpoint − feedback. Open-loop ignores feedback — load disturbances leave steady-state error.

Code lab

Code lab: a loop built from labelled blocks

The script writes each block as its own line — sensor, comparator, controller, actuator limit, plant — prints the first six ticks, then runs the same loop at 100 Hz, 20 Hz and 5 Hz. The plant has a little motor lag and a small gravity load. Run it with python3 loop_anatomy.py.

loop_anatomy.py · Python
# loop_anatomy.py - one control loop, built block by block, printed tick by tick.
# reference -> [compare] -> error -> [controller] -> command -> [actuator limit] -> [plant] -> output
#                 ^                                                                       |
#                 +------------------------- [sensor] <-----------------------------------+
# Plant: a joint whose speed follows the command with a little lag; a load pushes back.
# Then we run the SAME loop at 100 Hz, 20 Hz and 5 Hz to see why loop rate matters.

def make_loop(rate_hz, kp=8.0, verbose=False):
    dt_ctrl = 1.0 / rate_hz
    dt_sim = 0.001                        # the physical world runs "continuously" (1 ms steps)
    reference, angle, speed = 60.0, 0.0, 0.0
    LOAD = -5.0                           # deg/s of drag from gravity
    TAU = 0.05                            # s, motor speed lag
    MAX_CMD = 120.0                       # deg/s actuator limit
    command, next_ctrl, t = 0.0, 0.0, 0.0
    peak, rows = 0.0, []
    while t < 2.0:
        if t >= next_ctrl - 1e-12:        # ---- one control tick ----
            measured = round(angle, 1)                 # SENSOR (0.1 deg resolution)
            error = reference - measured               # COMPARATOR
            raw = kp * error                           # CONTROLLER (P)
            command = max(-MAX_CMD, min(MAX_CMD, raw)) # ACTUATOR limit
            if verbose and len(rows) < 6:
                rows.append((t, reference, measured, error, raw, command))
            next_ctrl += dt_ctrl
        # PLANT: speed lags behind the command, load drags it, angle integrates speed
        speed += (command - speed) / TAU * dt_sim
        angle += (speed + LOAD) * dt_sim
        peak = max(peak, angle)
        t += dt_sim
    return angle, peak, rows

final, peak, rows = make_loop(100, verbose=True)
print("First six ticks at 100 Hz (every 10 ms):")
print(f"{'t (s)':>6} {'ref':>5} {'meas':>6} {'error':>6} {'Kp*e':>7} {'cmd':>6}")
for r in rows:
    print(f"{r[0]:6.2f} {r[1]:5.0f} {r[2]:6.1f} {r[3]:6.1f} {r[4]:7.1f} {r[5]:6.1f}")
print("(cmd is clipped to 120 deg/s by the actuator limit at first)\n")

print("Same loop, same gain, different loop rates:")
for hz in (100, 20, 5):
    final, peak, _ = make_loop(hz)
    print(f"  {hz:>3} Hz: final {final:6.2f} deg, peak {peak:6.2f} deg, overshoot {max(0, peak-60):5.2f} deg")
print("\nSlower loops see the error later, so they react late and overshoot more.")

Output (run with python3 loop_anatomy.py)

First six ticks at 100 Hz (every 10 ms):
 t (s)   ref   meas  error    Kp*e    cmd
  0.00    60    0.0   60.0   480.0  120.0
  0.01    60    0.1   59.9   479.2  120.0
  0.02    60    0.3   59.7   477.6  120.0
  0.03    60    0.8   59.2   473.6  120.0
  0.04    60    1.3   58.7   469.6  120.0
  0.05    60    2.0   58.0   464.0  120.0
(cmd is clipped to 120 deg/s by the actuator limit at first)

Same loop, same gain, different loop rates:
  100 Hz: final  59.35 deg, peak  59.88 deg, overshoot  0.00 deg
   20 Hz: final  59.37 deg, peak  60.96 deg, overshoot  0.96 deg
    5 Hz: final  59.34 deg, peak  66.42 deg, overshoot  6.42 deg

Slower loops see the error later, so they react late and overshoot more.

Try it: change the loop rate and see how late the controller reacts. Find the slowest rate that still feels smooth.

Interactive · Loop timing budget

Too slow: loop misses its target rate
0 mstarget period 20.0 ms
Sensor read 3.00 msCompute 1.00 msSerial print 31.25 msdelay() 0.00 ms deadline

Wanted rate

50 Hz

Time used / loop

35.25 ms

CPU budget used

176 %

Actual rate

28.4 Hz

Serial time here = characters × 10 bits ÷ baud. On an Arduino Uno, Serial.print() returns at once while its small transmit buffer (64 bytes) has room; when you print more than the line can carry, print() waits — so in steady state each loop pays roughly this time.

Real world

Loop anatomy in real hardware

  • Hobby servo: reference = pulse width, sensor = internal potentiometer, controller + actuator = the servo’s board, motor and gears (SparkFun).
  • Industrial joint: outer position loop on an encoder; inner current loop in the amplifier (Modern Robotics, Fig. 11.1).
  • Cruise control: reference = set speed, sensor = vehicle speed, actuator = throttle and engine, disturbance = hills and wind (Michigan Control Tutorials).
  • Your bench: reference = SETPOINT, sensor = LDR, actuator = LED, plant = the light path, disturbance = your hand.
A small purple stepper driver carrier board plugged into the header sockets of a black controller board, next to motor connector cables
A DRV8825 stepper driver carrier — the power part of the actuator block. The microcontroller sends small logic signals; the driver switches the motor current from a separate supply. This is why GPIO pins never power motors directly.Photo: Ogoorcs · CC BY-SA 4.0 · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: a fixed-rate loop with every block labelled

Same LED + LDR circuit as Lesson 2, but the code is split into sensorBlock(), comparatorBlock(), controllerBlock() and actuatorBlock(), and the loop runs at a fixed rate set by LOOP_HZ. Cover the sensor and watch how quickly it recovers at 100, 20 and 5 Hz.

  1. Reuse the circuit

    Pin 9 → 220 Ω → LED → GND. 5 V → LDR → A0 → 10 kΩ → GND. LED pointing at the LDR, paper tube around both.

  2. Label your breadboard

    Stick small paper tags: SENSOR (LDR), ACTUATOR (LED), PLANT (the light path), CONTROLLER (Arduino). Saying the names aloud helps.

  3. Upload at 50 Hz

    Upload loop_anatomy.ino and open the Serial Plotter at 115200. Cover and uncover the sensor.

  4. Change the loop rate

    Set LOOP_HZ to 100, then 20, then 5. For each, cover the sensor for 3 s and count roughly how long it takes to settle after you uncover it.

  5. Find the bottleneck

    Change the print to every tick (n % 1) at 100 Hz. Does the loop still keep its rate? Print micros() differences to check.

loop_anatomy.ino · Arduino C++
// loop_anatomy.ino - the same light-keeping loop as light_keeper.ino, written block by block
// with a FIXED loop rate. Change LOOP_HZ (100, 20, 5) and watch how fast it settles after you
// cover the sensor. Wiring: pin 9 -> 220 ohm -> LED -> GND;  5V -> LDR -> A0 -> 10k -> GND.
const int LED_PIN = 9;
const int SENSOR_PIN = A0;
const int LOOP_HZ = 50;
const unsigned long PERIOD_US = 1000000UL / LOOP_HZ;

int reference = 600;          // REFERENCE (setpoint), counts 0..1023
const float KI_STEP = 0.05;   // controller: nudge output by KI_STEP * error each tick
float output = 0;             // controller memory
unsigned long nextTick = 0;

int sensorBlock()            { return analogRead(SENSOR_PIN); }
int comparatorBlock(int r, int y) { return r - y; }
float controllerBlock(int e) { output = constrain(output + KI_STEP * e, 0, 255); return output; }
void actuatorBlock(float u)  { analogWrite(LED_PIN, (int)u); }

void setup() {
  pinMode(LED_PIN, OUTPUT);
  Serial.begin(115200);
  Serial.println(F("ms,reference,measured,error,command"));
  nextTick = micros();
}

void loop() {
  if ((long)(micros() - nextTick) < 0) return;   // wait for the next tick
  nextTick += PERIOD_US;

  int y = sensorBlock();                 // SENSOR
  int e = comparatorBlock(reference, y); // COMPARATOR
  float u = controllerBlock(e);          // CONTROLLER
  actuatorBlock(u);                      // ACTUATOR -> PLANT (LED + air + LDR) -> SENSOR

  static int n = 0;
  if (++n % 5 == 0) {                    // print every 5th tick so Serial does not slow the loop
    Serial.print(millis()); Serial.print(',');
    Serial.print(reference); Serial.print(',');
    Serial.print(y); Serial.print(',');
    Serial.print(e); Serial.print(',');
    Serial.println((int)u);
  }
}

Debugging

Debugging along the chain

Check this blockQuestion to askHow to test
ReferenceIs the setpoint what I think, in the right units?Print it
SensorDoes the measurement match reality?Compare with a protractor / meter
ComparatorIs the sign right (r − y)?Move the plant below the setpoint; error must be positive
ControllerIs the command sensible for this error?Print e and u together
ActuatorDoes the motor/LED actually follow the command?Run the actuator open loop with fixed commands
PlantIs something mechanical blocking or slipping?Move it by hand with power off
Loop rateIs the loop running as fast as I think?Print the time between ticks

Think

Think about it

Think

Meera’s light keeper works perfectly at 50 Hz. She adds a long `Serial.println` of ten values every tick at 9600 baud, and now the brightness overshoots and wobbles after she uncovers the sensor. Nothing else changed. Which block or property of the loop did she break, and how should she fix it?

Experiment

Try it in the lab: label the blocks

About 30 minutes with the explorer, the script and the LED + LDR loop.

Experiment

Label the blocks

You will need

  • Control loop explorer (in your browser)
  • Loop timing lab (in your browser)
  • Notebook
  • Optional: `loop_anatomy.py`; Arduino UNO, LED, 220 Ω, LDR, 10 kΩ

Steps

  1. In the explorer, point to each block and say its name and the signal leaving it.
  2. Run `loop_anatomy.py`. For the first tick, write r, y, e, Kp·e and the clipped command.
  3. Record final angle and peak for 100, 20 and 5 Hz. Make a small table.
  4. In the loop timing lab, find the slowest rate that still feels smooth.
  5. Optional bench: run `loop_anatomy.ino` at 100, 20 and 5 Hz and note roughly how long it takes to settle after you uncover the sensor.

Interactive · Control loop explorer

Closed-loop control block diagram: setpoint, error, PID, plant, feedback

Mode

Closed

θ final

61.6°

Error

-1.6°

Closed-loop uses error = setpoint − feedback. Open-loop ignores feedback — load disturbances leave steady-state error.

Every loop has the same skeleton. When you can name each block and signal, and you know the loop rate, you can find almost any fault by walking around the diagram.

Knowledge check

Check your understanding

Knowledge check

1. The sensor in a joint loop measures…

2. The comparator (summing junction) computes…

3. In a robot joint, the plant is…

4. Why does feedback reject a disturbance added after the forward block?

5. Modern Robotics describes an inner loop in the motor amplifier that often controls…

6. In the code lab, the same gain gives more overshoot at 5 Hz because…

7. A 100 Hz loop has a period of…

8. In the first tick of the code lab, Kp × e = 480 °/s but the command is 120 °/s because…

9. The best way to keep a steady loop rate on an Arduino is…

10. When a loop misbehaves, a good first debugging step is…

Mini assignment

Hands-on assignment

Mini assignment

Anatomy sketch of your own loop

Draw, label and measure a complete feedback loop — your bench light keeper or a robot joint — including its loop rate.

Deliverables

  • A clean block diagram with all seven blocks and the four signals (r, e, u, y) labelled with real names and units from your loop.
  • The table of final angle and peak at 100, 20 and 5 Hz from `loop_anatomy.py`, plus one more rate of your choice.
  • If you built it: your measured loop period with and without printing every tick (use `micros()`).
  • A short nested-loop diagram for one joint of the 6DOF arm: which sensors and which inner loops would you expect?
  • A five-line “walk the loop” checklist you will use to debug future loops.

Do this, step by step

  1. Draw your loop with all seven blocks (reference, comparator, controller, actuator, plant, sensor, disturbance) and label r, e, u and y with real names and units.
  2. Run python3 loop_anatomy.py and copy the final angle and peak at 100, 20 and 5 Hz; add one more rate of your own and predict it before you run.
  3. Use the loop-timing widget above to find the slowest rate that still feels smooth.
  4. If you have the light keeper: flash loop_anatomy.ino (LOOP_HZ = 50), measure the loop period with micros(), then print every tick and measure again.
  5. Draw a nested-loop sketch for one 6DOF arm joint and write your five-line “walk the loop” checklist.

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: Draw the plant first in the middle, then the actuator arrow into it and the sensor arrow out of it.
  2. Hint 2: The comparator is just a circle with + for the reference and − for the measurement.
  3. Hint 3: The disturbance arrow points into the plant (or its output) — never into the controller.
  4. Hint 4: To measure the loop period, store micros() at each tick and print the difference every 50 ticks.

Challenges (pick by level)

  • 🟢 Easy: Label the seven blocks for a room AC with a thermostat.
  • 🟢 Easy: What is the loop period for 250 Hz?
  • 🟡 Medium: In loop_anatomy.py, add a disturbance at t = 1 s (subtract 10° from the angle). Compare recovery at 100 Hz and 5 Hz.
  • 🟡 Medium: Add a sensor delay of one tick (use the previous measurement). How does overshoot change at 20 Hz?
  • 🟠 Hard-ish: Turn the plant into two nested loops in Python: an inner speed loop at 1 kHz and an outer position loop at 100 Hz.
  • 🔴 Hard: On the bench, measure the LED+LDR response time by stepping the PWM and timing the reading change. What loop rate does that suggest?
  • ⚫ Research: Read *Modern Robotics* Figure 11.1 and its caption. Explain, in your own words, why the inner current loop must be faster than the position loop.

Next step

You know every block. In Lesson 5 — Proportional Control (P) you design the first real controller: push in proportion to the error, and discover what Kp does to speed, overshoot and leftover error.

Look back: Lesson 3: Setpoints, Sensors & Error. Next: Lesson 5: Proportional Control (P). Related: Stage 5 L07: Sense–Plan–Act Loop and Stage 10 — ROS 2 (ROS 2 control loops).

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