Stage 07 · Lesson 03/15

Control Systems & PID · Lesson 03

Setpoints, Sensors & Error

Est. 55–70 min

Why

Why a controller is only as good as its error signal

Every controller in this stage — P, I, D, PID — does one thing: it turns the error into a command. If the error is wrong, noisy, in the wrong units or has the wrong sign, the best controller in the world will do the wrong thing, confidently. So before we learn P, I and D, we make sure the error is something we can trust.

By the end of this lesson you will be able to: name the setpoint, measurement and error in any loop; convert raw sensor counts into real units; explain the resolution of a 10-bit ADC; reduce noise by averaging; add a dead band so a joint stops buzzing; handle the wrap-around trap for angles like 350° and 10°; and keep one sign convention — error = setpoint − measured — everywhere.

A rotary potentiometer with a round metal body, a long shaft on top and three solder terminals at the bottom
A rotary potentiometer — the simplest joint-angle sensor. The shaft moves a wiper along a resistive track, so the wiper voltage follows the angle. It is exactly what sits inside a hobby servo to measure its own shaft.Photo: Iainf · CC BY 2.5 · Source: Wikimedia Commons · resized, converted to WebP

Concept

Setpoint, measurement and error — done properly

Think of a cricket coach at the nets telling a bowler “pitch it on a good length — about 6 metres from the batter”. The setpoint is that length. The measurement is where the ball actually pitched, as the coach sees it. The error is the difference: “2 metres too short”. If the coach can’t see clearly (bad sensor), or says “too short” when it was too full (wrong sign), the bowler’s corrections make things worse. Good coaching starts with a good error.

The three words

Setpoint, measurement, error in different loops
LoopSetpoint (what you want)Measurement (sensor)Error
Robot joint90°Potentiometer / encoder: 84.5°+5.5°
Cruise control10 m/sWheel-speed sensor: 9.1 m/s+0.9 m/s
Balancing robot0° tiltGyro + accelerometer: −3°+3°
Light keeper (Lesson 2)600 countsLDR on A0: 540 counts+60 counts
Mobile robot heading10°Compass: 350°+20° (after wrapping!)

error = setpoint − measured (θe = θd − θ)

  • This is the convention in *Modern Robotics* (Section 11.2) and in the Michigan *Control Tutorials* (error = desired output − actual output). Positive error means “not there yet in the + direction”. Use it everywhere and your signs will always agree.

From counts to real units

The Arduino reference says analogRead() on an UNO maps 0 V to the operating voltage (5 V) onto whole numbers from 0 to 1023 — a 10-bit result. That number is not an angle yet. If your pot turns through, say, 270° from end to end, each count is 270 ÷ 1023 ≈ 0.264°. That is your resolution: the smallest change you can see. Always convert to real units (degrees, mm, m/s) *before* computing the error, and calibrate against a protractor because no pot is perfectly linear.

angle (°) = counts × (pot travel in °) ÷ 1023

  • Check your pot’s datasheet for its travel and measure the real end points — then correct the formula.
A heap of small rotary encoders with knurled metal shafts and green circuit-board bases, one in sharp focus in the centre
A rotary encoder (SparkFun). Instead of a voltage, it gives pulses as the shaft turns; the microcontroller counts them. More pulses per turn means finer resolution. Robot joints and wheels often use encoders — especially optical or magnetic ones, which have no rubbing track to wear out.Photo: SparkFun Electronics · CC BY 2.0 · Source: Wikimedia Commons · resized, converted to WebP

Noise: the shaky-scale problem

Real readings jitter by a few counts — electrical noise, a slightly loose wire, vibration. If the controller reacts to every flicker, the motor twitches. Two simple tools:

  • Averaging: read 8 or 16 times and take the mean. Noise cancels out; the true value stays. (Too much averaging makes the reading *late* — Lesson 12 covers that trade-off.)
  • Dead band: if the error is tiny (say under 1°), treat it as zero and hold. The joint stops chasing noise. The cost: it can rest anywhere inside the band.

The wrap-around trap

A compass says 350°; you want 10°. Naively, error = 10 − 350 = −340°, so the robot turns 340° the long way round. The truth is “20° to the right”. For anything that wraps around (headings, continuous joints), wrap the error into the range −180° to +180° first. The code lab has a three-line wrap180() function that does it.

A small blue circuit board labelled GY-521 with a square MPU-6050 sensor chip in the middle and a row of header pins along one edge
A GY-521 board with an MPU-6050 gyroscope and accelerometer. SparkFun’s gyroscope guide explains that MEMS gyros measure angular velocity, in degrees per second. A balancing robot uses readings like these to estimate its tilt — the measurement in its loop.Photo: Nevit Dilmen · CC BY-SA 3.0 · Source: Wikimedia Commons · resized, converted to WebP

Visual

Visualise it: watch the error

Change the setpoint and watch the **error** — the gap between what you want and what the sensor says. Positive error means the output is below the setpoint; the controller works to shrink it.

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: from raw counts to a trustworthy error

The script converts 10-bit readings to degrees, shows the resolution, computes the error from noisy readings, averages them, applies a dead band and fixes heading wrap-around. Run it with python3 setpoint_error.py.

setpoint_error.py · Python
# setpoint_error.py - turning a raw sensor reading into a trustworthy error.
# 1) A 10-bit ADC reads a potentiometer joint sensor (0..1023 counts over 0..270 deg).
# 2) We convert counts -> degrees, compute error = setpoint - measured, and see the
#    resolution limit, the effect of noise, a dead band, and the "wrap-around" trap for headings.
import random
random.seed(7)

POT_RANGE_DEG = 270.0       # example travel; check YOUR pot's datasheet
ADC_MAX = 1023              # 10-bit ADC on an Arduino UNO: 0..1023

def counts_to_deg(c):
    return c * POT_RANGE_DEG / ADC_MAX

def deg_to_counts(d):
    return round(d * ADC_MAX / POT_RANGE_DEG)

print("1) Resolution: one ADC count =", f"{POT_RANGE_DEG/ADC_MAX:.3f} deg", "\n")

setpoint = 90.0
print("2) Error with a noisy sensor (true angle 88.0 deg, noise +/-2 counts)")
true = 88.0
for i in range(5):
    c = deg_to_counts(true) + random.randint(-2, 2)
    m = counts_to_deg(c)
    print(f"   reading {i+1}: counts={c:4d}  measured={m:6.2f} deg  error={setpoint-m:+6.2f} deg")
avg = sum(counts_to_deg(deg_to_counts(true) + random.randint(-2, 2)) for _ in range(16)) / 16
print(f"   average of 16 readings: {avg:.2f} deg -> error {setpoint-avg:+.2f} deg\n")

print("3) Dead band: ignore errors smaller than 0.75 deg so the motor stops buzzing")
for e in (3.2, 0.9, 0.6, -0.4, -1.8):
    print(f"   error {e:+.1f} deg -> {'act' if abs(e) > 0.75 else 'hold (inside dead band)'}")
print()

def wrap180(e):
    """Shortest signed angle difference in (-180, 180]."""
    e = (e + 180.0) % 360.0 - 180.0
    return 180.0 if e == -180.0 else e

print("4) Heading wrap-around (a mobile robot's compass heading)")
for sp, meas in ((10, 350), (350, 10), (180, 0), (90, 45)):
    naive = sp - meas
    print(f"   setpoint {sp:3d}, measured {meas:3d}: naive error {naive:+5d}  ->  wrapped error {wrap180(naive):+6.1f}")
print("\nSign rule used everywhere in this stage: error = setpoint - measured.")
print("Positive error -> 'not there yet, keep going in the + direction'.")

Output (run with python3 setpoint_error.py)

1) Resolution: one ADC count = 0.264 deg 

2) Error with a noisy sensor (true angle 88.0 deg, noise +/-2 counts)
   reading 1: counts= 333  measured= 87.89 deg  error= +2.11 deg
   reading 2: counts= 332  measured= 87.62 deg  error= +2.38 deg
   reading 3: counts= 334  measured= 88.15 deg  error= +1.85 deg
   reading 4: counts= 331  measured= 87.36 deg  error= +2.64 deg
   reading 5: counts= 331  measured= 87.36 deg  error= +2.64 deg
   average of 16 readings: 87.84 deg -> error +2.16 deg

3) Dead band: ignore errors smaller than 0.75 deg so the motor stops buzzing
   error +3.2 deg -> act
   error +0.9 deg -> act
   error +0.6 deg -> hold (inside dead band)
   error -0.4 deg -> hold (inside dead band)
   error -1.8 deg -> act

4) Heading wrap-around (a mobile robot's compass heading)
   setpoint  10, measured 350: naive error  -340  ->  wrapped error  +20.0
   setpoint 350, measured  10: naive error  +340  ->  wrapped error  -20.0
   setpoint 180, measured   0: naive error  +180  ->  wrapped error +180.0
   setpoint  90, measured  45: naive error   +45  ->  wrapped error  +45.0

Sign rule used everywhere in this stage: error = setpoint - measured.
Positive error -> 'not there yet, keep going in the + direction'.

Try it: drag the A0 slider — that is your potentiometer turning a voltage into a 10-bit number. Convert a few readings to degrees in your notebook.

Interactive · GPIO / ADC / PWM Lab

Fake MCU board for digital out, analog in, and PWM duty. Browser-only — never talks to real USB/serial/hardware.

GPIO D7

Good for LEDs / logic — not motors.

ADC A0 (10-bit)

raw 512 → 2.50 V

Pot / distance proxy → robot perception.

PWM D9

duty 40%

PWM → driver → motor — never GPIO-direct.

board@sim ~ pins: D7=0 A0=512 D9=40% · educational MCU only

Real world

Sensors that close real loops

  • Hobby servos: an internal potentiometer measures the shaft (SparkFun).
  • Robot joints and wheels: encoders count pulses for position and speed.
  • Balancing robots and drones: gyros measure rotation rate; accelerometers sense the direction of gravity (SparkFun guides).
  • Cars: cruise control works from a measured vehicle speed — the same quantity your speedometer shows you.
  • Shops: digital scales show noisy readings and the shopkeeper uses a mental dead band.
A car speedometer dial with a red needle near 220 and markings from 0 to 220 kilometres per hour, with a green odometer display below the centre
A car speedometer in km/h. The needle is a measurement; the speed you choose to drive at is the setpoint; the difference is the error your foot corrects. Cruise control uses the same speed measurement electronically.Photo: Bluescan (sv.wikipedia) · Public domain · Source: Wikimedia Commons · resized, converted to WebP

Bench build

Bench build: a live error display

A potentiometer is your joint sensor. Type a setpoint in the Serial Monitor; the Arduino averages eight readings, converts them to degrees and prints the measured angle, the error and whether it is inside the dead band. Turn the knob and watch the error go to zero.

  1. Wire the pot

    Outer legs to 5 V and GND; middle leg (wiper) to A0.

  2. Upload and open the monitor

    Upload sensor_error.ino; Serial Monitor at 115200 baud, line ending “Newline”.

  3. Give a setpoint

    Type 90 and press Enter. Turn the knob until the error is inside ±1° and the line says “hold”.

  4. Check the sign

    Turn the knob *below* the setpoint: the error must be positive. Above it: negative. If not, swap the pot’s outer legs.

  5. Calibrate

    Tape a paper protractor under the knob. At 0°, 90° and 180°, note the reading and correct POT_RANGE_DEG so the printed angle matches.

sensor_error.ino · Arduino C++
// sensor_error.ino - read a joint sensor, convert to degrees, compute a clean error.
// A potentiometer on A0 is the joint sensor (outer legs to 5 V and GND, wiper to A0).
// Type a setpoint in degrees in the Serial Monitor (e.g. 90 then Enter).
// The sketch averages 8 readings, prints measured angle, error and whether it is in the dead band.
const int SENSOR_PIN = A0;
const float POT_RANGE_DEG = 270.0;  // check your pot's datasheet and calibrate
const float DEAD_BAND = 1.0;        // degrees
float setpoint = 90.0;

float readAngle() {
  long sum = 0;
  for (int i = 0; i < 8; i++) sum += analogRead(SENSOR_PIN);   // average out noise
  return (sum / 8.0) * POT_RANGE_DEG / 1023.0;
}

void setup() {
  Serial.begin(115200);
  Serial.println(F("Type a setpoint in degrees and press Enter"));
}

void loop() {
  if (Serial.available()) {
    float s = Serial.parseFloat();
    if (s >= 0 && s <= POT_RANGE_DEG) setpoint = s;
    while (Serial.available()) Serial.read();
  }
  float measured = readAngle();
  float error = setpoint - measured;         // the sign rule: setpoint - measured
  Serial.print(F("setpoint=")); Serial.print(setpoint, 1);
  Serial.print(F(" measured=")); Serial.print(measured, 1);
  Serial.print(F(" error="));   Serial.print(error, 1);
  Serial.println(fabs(error) <= DEAD_BAND ? F("  [in dead band: hold]") : F("  [act]"));
  delay(200);
}

Debugging

Debugging the error signal

SymptomLikely causeFix
Error has the wrong signPot wired the other way, or error computed as measured − setpointSwap the pot’s outer legs, or fix the formula to setpoint − measured
Reading jumps by 5–10 countsNoise, loose breadboard contact, long wiresAverage 8–16 readings; firm connections; short wires
Printed angle wrong at the endsPot travel not 270°, or not linearCalibrate with a protractor at three points
Robot turns the long way roundNo wrap-around on heading errorUse wrap180() before the controller
Joint buzzes at the targetController chasing tiny errorsAdd a small dead band
Joint stops a bit off targetDead band too wideMake it narrower, or improve the sensor

Think

Think about it

Think

Arjun’s turntable robot must face a heading of 5°. Its compass says 358°. His code does `error = 5 - 358` and the robot spins almost a full circle every time. Meanwhile Meera’s arm joint buzzes and gets warm while “holding” at 90°. Diagnose both problems and give each a one-line fix.

Experiment

Try it in the lab: build an error journal

About 30 minutes with the explorer, the script and a potentiometer.

Experiment

Build an error journal

You will need

  • Control loop explorer (in your browser)
  • Notebook
  • Optional: `setpoint_error.py`; Arduino UNO, 10 kΩ potentiometer, paper protractor

Steps

  1. In the explorer, set three different setpoints and write the error at the start of each move. Check the sign each time.
  2. Run `setpoint_error.py`. Copy the five noisy errors and the averaged error.
  3. Change the noise to ±10 counts and find how many readings you need to average to get within 0.5° of the true error.
  4. Work out the wrapped error by hand for (setpoint 20°, measured 340°) and (setpoint 300°, measured 30°). Check with the script.
  5. Optional bench: run `sensor_error.ino`, calibrate at 0°, 90° and 180°, and note how many counts the reading jumps when you don’t touch the knob.

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.

A clean error needs the right units, a known resolution, a little averaging, a sensible dead band and a fixed sign rule. With those, every controller you build next has something solid to work with.

Knowledge check

Check your understanding

Knowledge check

1. Error is usually defined as…

2. Bad sensor data causes…

3. An Arduino UNO’s `analogRead()` returns values from…

4. A pot travels 270° over 0–1023 counts. Its resolution is about…

5. Averaging 16 readings mainly helps by…

6. A dead band of ±1° means…

7. Setpoint 10°, compass 350°. The correct heading error is…

8. `error = 90 - analogRead(A0)` is wrong because…

9. A MEMS gyroscope measures…

10. To check the sign of your error on the bench you should…

Mini assignment

Hands-on assignment

Mini assignment

Sensor checklist and error journal

Make one real sensor trustworthy: units, resolution, noise, sign, dead band — and prove it with numbers.

Deliverables

  • A sensor checklist for your potentiometer (or the simulated one): units, range, resolution, measured noise in counts and degrees.
  • A calibration table with readings at 0°, 90° and 180°, and your corrected conversion formula.
  • Output from `setpoint_error.py` with noise changed to ±10 counts, and the number of readings you need to average for 0.5° accuracy.
  • Hand-worked wrap-around errors for three heading pairs of your choice, checked with `wrap180()`.
  • One paragraph: what dead band would you choose for the 6DOF arm’s gripper joint, and why?

Do this, step by step

  1. Wire the potentiometer to A0 and flash sensor_error.ino; note the raw count at both ends of travel and the middle.
  2. Measure the pot at 0°, 90° and 180° with a protractor, write the raw counts, and correct the conversion (POT_RANGE_DEG = 270.0, ADC_MAX = 1023).
  3. Hold the knob still for 10 seconds and write the noise in counts and in degrees (1 count ≈ 270 ÷ 1023 ≈ 0.26°).
  4. In setpoint_error.py change the noise to ±10 counts, run it, and find how many readings you must average for 0.5° accuracy.
  5. Work out three wrap-around heading errors by hand (e.g. target 170°, measured −170°), check each with wrap180(), then choose a gripper dead band and justify it in one paragraph.

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: Resolution = travel ÷ 1023 for a 10-bit reading.
  2. Hint 2: Measure noise by not touching the knob and watching the highest and lowest reading for 10 s.
  3. Hint 3: For wrap-around: add 180, take modulo 360, subtract 180.
  4. Hint 4: A sensible dead band is a little bigger than the noise but much smaller than the accuracy you need.

Challenges (pick by level)

  • 🟢 Easy: A 12-bit ADC gives 0–4095. What is the resolution for the same 270° pot?
  • 🟢 Easy: Name the setpoint, sensor and error for an AC thermostat.
  • 🟡 Medium: Add a moving average (last 8 readings) to sensor_error.ino instead of 8 back-to-back reads. Compare the jitter.
  • 🟡 Medium: Add hysteresis to the dead band: start acting at 1.5°, stop at 0.5°. Why does this help?
  • 🟠 Hard-ish: Modify setpoint_error.py to measure how much delay a 16-sample moving average adds when the angle ramps at 30 °/s.
  • 🔴 Hard: Read an encoder with interrupts and print the error in degrees. Compare its resolution with the pot.
  • ⚫ Research: Read SparkFun’s *Gyroscope* and *Accelerometer Basics* guides and explain why balancing robots combine both sensors to measure tilt.

Next step

In Lesson 4 — Control Loop Anatomy you put every block on the table — reference, comparator, controller, actuator, plant, sensor, disturbance — and see why the loop rate matters as much as the gain.

Look back: Lesson 2: Open Loop vs Closed Loop. Next: Lesson 4: Control Loop Anatomy. Related: Stage 4 L08: Analog Signals & ADC, Stage 5 L06: Sensors & Proprioception and Stage 1 — Math for Robotics.

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