71  PID Control Fundamentals

In 60 Seconds

A PID controller calculates output as the sum of three terms: Proportional (reacts to current error), Integral (accumulates past errors), and Derivative (predicts future error trend). The proportional term alone cannot eliminate steady-state error – a heater set to 25C with P-only control will stabilize at 23-24C.

71.1 Learning Objectives

By the end of this chapter, you will be able to:

  • Explain PID Components: Describe the three components of a PID controller and their individual roles
  • Calculate Error Signals: Compute error, proportional output, and controller response for a given setpoint and measurement
  • Evaluate Proportional Control: Assess how proportional gain affects response speed, overshoot, and steady-state error
  • Identify P-Only Limitations: Diagnose when proportional-only control is insufficient and justify adding I or D terms
  • Apply the PID Equation: Calculate total controller output from P, I, and D term contributions

71.2 PID (Proportional-Integral-Derivative) Control

Block diagram of PID controller showing error signal splitting into three parallel paths: Proportional term (Kp times error for immediate response), Integral term (Ki times accumulated error for steady-state correction), and Derivative term (Kd times error rate for overshoot prevention), all summing to produce final control output
Figure 71.1: PID control system block diagram showing the three parallel control actions: Proportional (responds to current error), Integral (eliminates steady-state error), and Derivative (anticipates future error)

While simple closed-loop systems provide basic feedback, achieving optimal performance often requires more sophisticated control algorithms. The PID controller is the most widely used feedback control algorithm in industrial and IoT applications.

71.2.1 PID Overview

Block diagram of a closed-loop feedback control system with setpoint input, error calculation, PID controller, plant/process, and sensor feedback path
Figure 71.2: Closed-loop feedback control system showing setpoint, controller, plant, and sensor in a continuous loop

A PID controller uses three different control strategies simultaneously, each addressing different aspects of error correction:

  1. P (Proportional): Reacts to current error magnitude
  2. I (Integral): Reacts to accumulated error over time
  3. D (Derivative): Reacts to rate of error change

Imagine you’re driving on a highway and need to change lanes. Your brain performs PID control naturally:

71.2.2 Proportional (P) - React to the Error

  • Situation: You’re 2 feet from where you want to be
  • Response: Turn the steering wheel proportionally - bigger error = bigger turn
  • Problem: If you only use P, you’ll overshoot and oscillate!

71.2.3 Integral (I) - Eliminate Steady-State Error

  • Situation: A crosswind keeps pushing you right
  • Response: You notice you’re always a bit off, so you hold the wheel slightly left
  • The I term accumulates past errors and corrects persistent bias
  • Real IoT example: Temperature sensor with consistent 0.5C offset

71.2.4 Derivative (D) - Anticipate and Dampen

  • Situation: You’re approaching your target lane fast
  • Response: You start turning back before you reach it to avoid overshooting
  • The D term predicts future error based on rate of change
  • Real IoT example: Slowing down a motor before it hits the target position

71.2.5 The Complete Picture

Term Responds To Fixes Danger If Too High
P Current error Immediate deviation Oscillation
I Accumulated error Persistent bias Overshoot, instability
D Rate of change Overshoot Noise amplification

Key insight: Most IoT control uses PI (no derivative) because sensor noise makes D unstable. Only use D when you have clean, high-frequency data!

PID controller block diagram showing error signal splitting into three parallel paths: Proportional term multiplied by Kp for immediate proportional response, Integral term accumulating error over time multiplied by Ki to eliminate steady-state offset, Derivative term using rate of change multiplied by Kd to reduce overshoot, all three summing to produce the final control signal
Figure 71.3: PID controller: P, I, D terms summed for control signal

PID Controller Block Diagram: Error signal splits into three parallel paths. P term responds to current error, I term accumulates past errors, D term predicts future based on rate of change. All three combine to produce optimal control signal.

PID Equation:

\[ u(t) = K_p \cdot e(t) + K_i \cdot \int_{0}^{t} e(\tau) \, d\tau + K_d \cdot \frac{de(t)}{dt} \]

Where: - \(u(t)\) = Controller output at time \(t\) - \(e(t)\) = Error (Set Point - Process Variable) - \(K_p\) = Proportional gain - \(K_i\) = Integral gain - \(K_d\) = Derivative gain

Common PID Combinations:

Table 71.1: PID Mode Combinations
Mode Usage Application Examples
P Sometimes Simple temperature control, LED brightness
PI Most common HVAC systems, level control, pressure regulation
PID Sometimes Motor speed control, precision positioning
PD Rare Servo motors, fast response systems

71.3 Understanding Error in PID Control

The foundation of PID control is the error signal:

Process Variable (PV):
The actual measured value of what we’re controlling (e.g., current temperature)
Set Point (SP):
The desired target value (e.g., target temperature)
Error (e):
The difference between desired and actual values

\[ e(t) = SP - PV(t) \]

PID temperature control example showing room starting at 18C with target 22C creating +4C error, proportional term providing strong initial heating, integral term accumulating error over time, derivative term detecting rapid temperature rise and reducing heating to prevent overshoot, system smoothly reaching and maintaining 22C setpoint
Figure 71.4: Practical example of PID control applied to home temperature control system showing sensor feedback, error calculation, and combined P+I+D control actions
PID temperature control sequence diagram showing room starting at 18 degrees Celsius with 22 degree setpoint creating 4-degree error, proportional term providing strong initial heating output, integral term accumulating positive error over time, derivative term detecting rapid temperature rise and applying braking, system smoothly approaching and maintaining 22 degrees Celsius without overshoot
Figure 71.5: Home heating: 18C to 22C using P, I, D components

PID Temperature Control Sequence: Initially large error (18-22C) produces full heating. As temperature rises, P term decreases (smaller error), D term provides braking (rapid approach), and system smoothly reaches setpoint without overshoot.

Scenario Analysis:

Table 71.2: Temperature Control Timeline
Time SP PV Error Action
0 min 22C 18C +4C Full heating
5 min 22C 20C +2C Reduce heating
10 min 22C 21.5C +0.5C Minimal heating
15 min 22C 22C 0C Heating OFF
20 min 22C 21.8C +0.2C Small heating pulse

Key Observations:

  • As error decreases, control action decreases
  • Zero error means no action needed (maintain state)
  • Small variations around set point are normal

71.4 Proportional Control (P)

Diagram of proportional-only control system showing error input multiplied by proportional gain Kp to produce control output directly proportional to current error magnitude, with large errors producing strong corrections and small errors producing weak corrections, demonstrating fast response but potential steady-state offset
Figure 71.6: Proportional control system diagram showing output proportional to current error magnitude - immediate response but may have steady-state error

The Proportional term provides control action directly proportional to the current error. Larger errors produce stronger corrections.

\[ u_p(t) = K_p \cdot e(t) \]

For a smart thermostat with \(K_p = 5\), if the room is at 18°C and setpoint is 22°C:

  • Error: \(e = 22 - 18 = 4°C\)
  • Output: \(u_p = 5 \times 4 = 20\) (20% heater power)

As temperature rises to 20°C, error drops to 2°C, so output reduces to \(5 \times 2 = 10\) (10% power). At 21°C, only 5% power remains. This is why P-only can’t reach 22°C exactly—when error shrinks below 0.5°C, output becomes too weak (2.5%) to overcome heat loss, leaving permanent offset.

Proportional control mechanism diagram showing current error signal multiplied by gain Kp to produce proportional output, with examples showing large error producing large correction and small error producing small correction, illustrating fast immediate response characteristic of P-term
Figure 71.7: Proportional: output = Kp times error magnitude

Proportional Control Mechanism: Output directly proportional to error magnitude. Large errors produce strong corrections, small errors produce weak corrections. Simple but may leave steady-state offset.

Characteristics:

  • Fast response: Immediate reaction to errors
  • Simple implementation: Single multiplication
  • Proportional output: Big errors = big corrections; small errors = small corrections
Analogy: Driving and Lane Changes

Imagine changing lanes on a highway (the “process”) by steering (the “control action”):

Set Point (SP): Center of target lane Process Variable (PV): Current car position Error: Distance from center of target lane

Lane change analogy diagram comparing three Kp tuning values: low Kp showing slow gentle steering response that barely reaches target lane, moderate Kp showing balanced smooth transition to target lane, and high Kp showing aggressive fast turn that overshoots and oscillates across the target lane
Figure 71.8: Kp tuning: low (slow), moderate (balanced), high (overshoot)

Kp Tuning Impact on Lane Change: Low Kp produces slow, gentle response that may never reach target. Moderate Kp balances speed and stability. High Kp causes fast but unstable response with overshoot and oscillation.

Kp Selection Impact:

Table 71.3: Impact of Proportional Gain
Kp Value Steering Behavior System Response Issues
Small Kp (0.1) Gentle turns Slow lane change May never reach target
Moderate Kp (0.5) Smooth transitions Good balance Acceptable performance
Large Kp (2.0) Aggressive turns Fast lane change Overshoot, oscillation

Proportional Control Response:

Proportional-only control timeline graph showing temperature rising rapidly from 18 degrees with large initial error, control output decreasing as temperature approaches setpoint, system settling at 21.7 degrees with persistent 0.3-degree steady-state error because remaining small error produces insufficient control output to overcome heat loss
Figure 71.9: P-only control: steady-state error persists at equilibrium

Proportional-Only Control Timeline: Fast initial response due to large error, but as error decreases, control action weakens. System settles with persistent steady-state error because small remaining error produces insufficient control output.

Problems with P-Only Control:

  1. Steady-State Error: System may never reach exact set point
  2. Overshoot: High Kp causes system to go past target
  3. Oscillation: High Kp can cause continuous cycling around set point
  4. Cannot handle disturbances: External forces cause permanent offset
P-Only Control Limitation: Steady-State Error
Graph comparing three proportional-only control responses over time: low Kp shows slow gentle approach settling below setpoint with steady-state error, moderate Kp shows balanced response reaching near setpoint with small offset, high Kp shows fast aggressive response with large overshoot and sustained oscillation around setpoint
Figure 71.10: Graph comparing proportional control responses with different Kp values - higher Kp gives faster response but more oscillation

With proportional control alone, there’s often a permanent offset from the set point called steady-state error.

Why?

  • As error decreases, control action decreases
  • Eventually, control action becomes too weak to eliminate remaining error
  • System settles with small persistent error

Example:

  • Set point: 22C
  • Steady state: 21.7C
  • Error: 0.3C persists indefinitely
  • P-only control cannot eliminate this offset

Solution: Add Integral control to eliminate steady-state error

PID control is like three friends helping you ride a bike in a perfectly straight line!

71.4.1 The Sensor Squad Adventure: The Bike Race

Sammy the Sensor, Lila the LED, and Max the Microcontroller entered a bike race where they had to ride in a perfectly straight line. But it was HARD! The wind kept pushing them sideways!

Friend P (Proportional) was the first helper. “I’ll tell you HOW FAR you are from the line!” said P. “If you’re way off to the right, steer LEFT a lot! If you’re just a tiny bit off, steer just a tiny bit!” P was great at reacting quickly, but there was a problem – the wind kept pushing, and P could never quite get them perfectly on the line.

Friend I (Integral) joined next. “I notice you’ve been a LITTLE bit off to the right for a long time now,” said I. “Even though P thinks the error is small, I’ve been adding it up, and it’s a LOT of small errors! Let me steer a bit more to fix that!” I was like a friend with a REALLY good memory who keeps track of all past mistakes.

Friend D (Derivative) arrived last. “WHOA, you’re heading toward the line REALLY fast!” shouted D. “If you don’t slow down, you’ll zoom right past it! Let me ease off the steering before you overshoot!” D was like having a friend who can see the future and warns you before things go wrong.

Together, P (reacts to NOW), I (remembers the PAST), and D (predicts the FUTURE) kept the bike perfectly on the line!

71.4.2 Key Words for Kids

Word What It Means
Proportional (P) Reacts based on how far off you are RIGHT NOW
Integral (I) Remembers all past mistakes and fixes the total
Derivative (D) Predicts what will happen next and slows you down before overshooting
Setpoint The perfect line you’re trying to follow

71.4.3 Try This at Home!

Fill a cup with water to EXACTLY the halfway mark. First try pouring fast without stopping (P-only – you’ll probably overshoot!). Now try slowing down as you get close (that is your D term!). See how PID thinking helps you get the perfect level!

Key Takeaway

A PID controller combines three complementary strategies: Proportional reacts to the current error magnitude (how far off), Integral accumulates past errors to eliminate persistent offset (how long you have been off), and Derivative responds to the rate of change (how fast things are changing). Proportional alone leaves steady-state error. PI (the most common configuration) eliminates that error. Full PID adds damping to minimize overshoot. For most IoT applications, PI control suffices – add D only when overshoot causes real problems and sensor data is clean enough to avoid noise amplification.

71.5 Hands-On: PID Controller Implementation

Theory is essential, but seeing PID in action makes the concepts concrete. The code below implements a PID controller for temperature regulation – the most common IoT control application. You can run the Python version on any computer, and the Arduino version on an ESP32.

71.5.1 Python PID Simulator: P-Only vs PI vs PID

This simulation models a heater controlling room temperature. It compares three controller modes so you can directly see steady-state error, overshoot, and settling time.

class PIDController:
    """Discrete PID controller for IoT actuator control."""
    def __init__(self, kp, ki=0.0, kd=0.0, output_min=0, output_max=100):
        self.kp, self.ki, self.kd = kp, ki, kd
        self.output_min, self.output_max = output_min, output_max
        self.integral, self.prev_error = 0.0, 0.0

    def compute(self, setpoint, measured, dt):
        error = setpoint - measured
        p_term = self.kp * error
        self.integral += error * dt
        i_term = self.ki * self.integral
        d_term = self.kd * ((error - self.prev_error) / dt if dt > 0 else 0)
        self.prev_error = error
        output = max(self.output_min, min(self.output_max, p_term + i_term + d_term))
        return output, p_term, i_term, d_term

def simulate_room(heater_pct, temp, ambient=15.0, dt=1.0):
    """Thermal model: heater gain vs Newton's cooling law."""
    return temp + heater_pct * 0.005 * dt - 0.01 * (temp - ambient) * dt

Comparing P-only, PI, and PID on a room heating scenario (setpoint 22 C, ambient 15 C):

controllers = {
    "P-only (Kp=8)":          PIDController(kp=8.0),
    "PI (Kp=8, Ki=0.3)":     PIDController(kp=8.0, ki=0.3),
    "PID (Kp=8, Ki=0.3, Kd=2)": PIDController(kp=8.0, ki=0.3, kd=2.0),
}
temps = {name: 18.0 for name in controllers}

for t in range(0, 301, 10):
    for name, pid in controllers.items():
        for _ in range(10 if t > 0 else 1):
            out, _, _, _ = pid.compute(22.0, temps[name], 1.0)
            temps[name] = simulate_room(out, temps[name])

# Result at t=300s:
# P-only:  ~21.6 C (steady-state error persists)
# PI:      22.0 C  (error eliminated, some overshoot)
# PID:     22.0 C  (error eliminated, minimal overshoot)

What to observe: P-only control never reaches exactly 22 C – it stabilizes around 21.5-21.7 C because the control output becomes too weak as the error shrinks. PI eliminates this offset by accumulating the error over time. PID adds the derivative term that slows the approach and prevents overshoot. These correspond exactly to the driving analogy in the For Beginners section above.

71.5.2 Arduino/ESP32: Real PID Temperature Controller

This C++ implementation runs on an ESP32 with a thermistor (temperature sensor) and a relay or MOSFET-controlled heater. It uses the same PID algorithm as the Python version above.

// --- ESP32 PID Temperature Controller ---
// Hardware: thermistor on GPIO34 (ADC), heater relay on GPIO25 (PWM)

const int SENSOR_PIN = 34;    // Thermistor analog input
const int HEATER_PIN = 25;    // Heater PWM output (0-255)
const float SETPOINT = 22.0;  // Target temperature (C)

// PID gains -- tuned for a small room heater
// Start with Kp only, then add Ki, then Kd (Ziegler-Nichols approach)
float Kp = 25.0;   // Proportional: strong response to error
float Ki = 0.8;     // Integral: eliminate steady-state offset
float Kd = 5.0;     // Derivative: reduce overshoot

// PID state variables
float integral = 0.0;
float prev_error = 0.0;
unsigned long prev_time = 0;

float readTemperature() {
  // Read thermistor via voltage divider (10k NTC + 10k resistor)
  int raw = analogRead(SENSOR_PIN);
  float voltage = raw * 3.3 / 4095.0;
  // Steinhart-Hart approximation for 10k NTC thermistor
  float resistance = 10000.0 * voltage / (3.3 - voltage);
  float tempK = 1.0 / (1.0/298.15 + (1.0/3950.0) * log(resistance/10000.0));
  return tempK - 273.15;  // Convert Kelvin to Celsius
}

float computePID(float setpoint, float measured, float dt) {
  float error = setpoint - measured;

  // P term
  float p_term = Kp * error;

  // I term with anti-windup clamping
  integral += error * dt;
  integral = constrain(integral, -50.0, 50.0);  // Prevent runaway integral
  float i_term = Ki * integral;

  // D term (on measurement, not error, to avoid derivative kick)
  float derivative = (error - prev_error) / dt;
  float d_term = Kd * derivative;
  prev_error = error;

  // Sum and clamp to PWM range (0-255)
  float output = p_term + i_term + d_term;
  return constrain(output, 0, 255);
}

void setup() {
  Serial.begin(115200);
  analogReadResolution(12);       // ESP32 12-bit ADC
  ledcSetup(0, 1000, 8);         // PWM channel 0, 1kHz, 8-bit
  ledcAttachPin(HEATER_PIN, 0);
  prev_time = millis();

  Serial.println("Time(s), Temp(C), Setpoint(C), Output(%), Error(C)");
}

void loop() {
  unsigned long now = millis();
  float dt = (now - prev_time) / 1000.0;  // Convert ms to seconds
  if (dt < 0.5) return;  // Run PID at 2 Hz (every 500ms)
  prev_time = now;

  float temperature = readTemperature();
  float output = computePID(SETPOINT, temperature, dt);

  // Drive heater via PWM
  ledcWrite(0, (int)output);

  // Log CSV data for plotting
  float error = SETPOINT - temperature;
  Serial.printf("%.1f, %.2f, %.1f, %.1f, %.2f\n",
    now / 1000.0, temperature, SETPOINT, output * 100.0 / 255.0, error);
}

What to observe: Upload this to an ESP32 with a thermistor and heater. Open the Serial Plotter to watch the temperature approach the setpoint. Try setting Ki = 0 and Kd = 0 to see P-only behavior (steady-state error). Then add Ki = 0.8 to see the offset eliminated. Finally add Kd = 5.0 to see reduced overshoot. The constrain(integral, -50, 50) line prevents integral windup – a common bug where the integral term grows unbounded during large sustained errors (like during startup).

71.5.3 Ziegler-Nichols Tuning Quick Reference

The Ziegler-Nichols method provides starting-point PID gains without a mathematical model of the plant:

  1. Set Ki = 0, Kd = 0. Increase Kp until the system oscillates with constant amplitude. Record this as Ku (ultimate gain) and Tu (oscillation period).
  2. Calculate gains from the table:
Controller Kp Ki Kd
P-only 0.50 Ku
PI 0.45 Ku 0.54 Ku / Tu
PID 0.60 Ku 1.2 Ku / Tu 0.075 Ku Tu

For example, if Ku = 40 and Tu = 8 seconds:

  • PID gains: Kp = 24, Ki = 6.0, Kd = 24.0
  • Start here, then fine-tune based on observed response

Scenario: A smart home thermostat controls a heating system for a room. Initial testing with P-only control (Kp=5) reveals steady-state error: setpoint 22°C, but room stabilizes at 21.3°C (0.7°C error).

Step 1: Analyze P-Only Steady-State Error

  • Error at steady state: 22°C - 21.3°C = 0.7°C
  • P-only output: u = Kp × e = 5 × 0.7 = 3.5 (heater %)
  • Problem: 3.5% heater power exactly balances heat loss, but can’t reach 22°C

Step 2: Add Integral Term to Eliminate Offset

  • Switch to PI control: u(t) = Kp·e(t) + Ki·∫e(τ)dτ
  • Choose Ki = 0.3 (using Ziegler-Nichols PI formula: Ki = 0.54 Ku / Tu)

Step 3: Simulate PI Response Time series showing error accumulation and elimination:

Time Temp (°C) Error (°C) P term I term (integral) Total Output Note
0 min 18.0 +4.0 20.0 0.0 20.0 Full heating
5 min 20.5 +1.5 7.5 6.0 13.5 I accumulating
10 min 21.5 +0.5 2.5 9.0 11.5 Near setpoint
15 min 21.9 +0.1 0.5 10.8 11.3 I keeps pushing
20 min 22.0 0.0 0.0 12.0 12.0 Zero error!
25 min 22.0 0.0 0.0 12.0 12.0 Maintained

Key Observations:

  1. P term alone (row 10 min): 2.5% output insufficient to eliminate 0.5°C error
  2. I term accumulates: Even small errors add up (0.5°C × 10 min × Ki=0.3 → +9.0)
  3. Steady-state output: PI control settles at 12% heater power (vs P-only’s 3.5%)
  4. Error elimination: Integral term continues increasing until error reaches exactly 0°C

Step 4: Calculate Integral Windup Protection Problem: If door is left open (large disturbance), error stays at +5°C for 30 minutes. Integral term accumulates to 45 (5 × 30 × 0.3), causing massive overshoot when door closes.

Solution: Anti-Windup Clamp

integral = constrain(integral, -20, 20)  # Limit accumulation
  • Maximum I contribution: 20 × Ki = 20 × 0.3 = 6% heater
  • Prevents overshoot while maintaining error elimination

Measured Performance:

  • P-only: Steady-state error = 0.7°C, settling time = 8 min
  • PI: Steady-state error = 0.0°C, settling time = 20 min (slower but accurate)
  • PI with anti-windup: Zero error, 18 min settling, no overshoot on disturbances

Energy Efficiency Bonus: Zero steady-state error means heater runs at optimal power (12%) instead of cycling on/off due to persistent offset. This saves 15-20% energy vs bang-bang control.

Application Steady-State Error Tolerance Overshoot Tolerance Sensor Noise Recommended Controller Justification
LED dimming High (±5%) High Low P-only Fast response, no precision needed
Room HVAC Zero required Moderate (±1°C) Low PI Eliminate offset, minor overshoot OK
Water tank level Zero required Low (<5%) Low PID No overshoot, damped approach
Motor speed control Low (±2%) Very Low (<1%) Medium PID with filter Tight control, noise rejection
Incubator temperature Zero required Zero (life-critical) Medium PI + feedforward Perfect tracking, no overshoot

Decision Tree:

  1. Can you tolerate steady-state error?
    • YES (error <5% acceptable) → Use P-only (simplest, fastest)
    • NO (must reach exact setpoint) → Continue to step 2
  2. Is overshoot dangerous or costly?
    • YES (overshoot causes damage/waste) → Continue to step 3
    • NO (minor overshoot acceptable) → Use PI (eliminates error, simple)
  3. How noisy is your sensor?
    • Low noise (<1% reading) → Use PID (derivative adds damping)
    • High noise (>5% reading) → Use PI only (D amplifies noise)
  4. Do you have a predictable disturbance?
    • YES (e.g., heater has known delay) → Add feedforward term
    • NO → Stick with PI or PID

Real-World Examples with Specific Gains:

System Controller Kp Ki Kd Why
Smart bulb P 0.8 - - 20% brightness error acceptable, instant response valued
Home thermostat PI 5.0 0.3 - Zero error required, 1-2°C overshoot OK, cheap sensor (clean signal)
Industrial oven PID 8.0 0.5 3.0 Precision ±0.5°C, no overshoot (product damage), fast thermal response
Motor position PID 15 1.2 8.0 Zero error, no overshoot (mechanical stress), encoder has low noise
pH neutralization PI 2.0 0.1 - Zero offset required, but derivative useless (chemical delay)

Common Tuning Mistakes:

  • Too high Kp: Oscillation (hunting around setpoint)
  • Too high Ki: Integral windup → massive overshoot
  • Too high Kd: Noise amplification → erratic control, chattering
  • Forgetting anti-windup: Integral saturates → 10-30 minute recovery time after disturbances

Quick Start Tuning Method (Ziegler-Nichols):

  1. Set Ki=0, Kd=0. Increase Kp until system oscillates with constant amplitude.
  2. Record Ku (ultimate gain causing oscillation) and Tu (oscillation period).
  3. For PI: Kp = 0.45×Ku, Ki = 0.54×Ku/Tu
  4. For PID: Kp = 0.6×Ku, Ki = 1.2×Ku/Tu, Kd = 0.075×Ku×Tu
  5. Fine-tune by ±20% based on observed performance.

Key Insight: For 80% of IoT control applications, PI is optimal – it eliminates steady-state error (which P-only can’t do) without the complexity and noise sensitivity of PID. Only use PID when overshoot must be minimized and you have a clean sensor signal.

Common Mistake: Using PID with Noisy Sensors

The Error: Applying full PID control (including derivative term) to a noisy temperature sensor, causing the heater to oscillate wildly.

Scenario: A DIY smart greenhouse controller uses a cheap DHT22 temperature sensor (±0.5°C accuracy, reads every second) with PID control tuned as Kp=10, Ki=0.5, Kd=5.

What Happens:

  • Sensor reading at t=0: 22.3°C
  • Sensor reading at t=1: 21.8°C (noise, not real change)
  • Derivative calculation: de/dt = (22.3 - 21.8) / 1s = 0.5°C/s
  • D term output: Kd × de/dt = 5 × 0.5 = 2.5 (massive correction for noise!)

Over 10 seconds:

Time Temp Reading Error P term D term (noise!) Total Output Heater Action
0s 22.3°C -0.3 -3.0 0.0 -3.0 OFF
1s 21.8°C +0.2 +2.0 +2.5 +4.5 ON (noise spike!)
2s 22.1°C -0.1 -1.0 -1.5 -2.5 OFF
3s 22.0°C 0.0 0.0 +0.5 +0.5 ON
4s 22.2°C -0.2 -2.0 -1.0 -3.0 OFF

Result: Heater cycles ON/OFF every 1-2 seconds due to sensor noise being amplified by the derivative term. This causes: 1. Relay wear (10,000 cycles instead of designed 100/day → failure in weeks) 2. Temperature instability (±1°C fluctuations vs target ±0.2°C) 3. Energy waste (50% more power due to thermal cycling losses)

The Fix (Three Options):

Option 1: Remove D term entirely (use PI instead)

output = Kp * error + Ki * integral  # No derivative term
  • Result: Smooth control, 0.2°C stability, relay cycles 4-6 times/hour
  • Trade-off: Slightly slower response to setpoint changes (+30 seconds)

Option 2: Filter the derivative term (low-pass filter)

filtered_de = 0.7 * previous_de + 0.3 * current_de  # Exponential filter
d_term = Kd * filtered_de
  • Result: D term smoothed, reduces noise amplification by 70%
  • Trade-off: D term lags by 2-3 seconds (less effective damping)

Option 3: Derivative on measurement (not error)

d_term = -Kd * (current_temp - previous_temp) / dt  # Derivative of PV, not error
  • Result: Avoids “derivative kick” when setpoint changes, but still noise-sensitive

Measured Performance Comparison:

Configuration Temperature Stability Relay Cycles/Hour Overshoot on Setpoint Change
PID (Kd=5, raw) ±1.0°C (noise amplified) 300+ (excessive) 0.5°C (well-damped)
PI (Kd=0) ±0.2°C 5 1.2°C (acceptable)
PID (Kd=5, filtered) ±0.4°C 30 0.8°C
PID (D-on-PV, Kd=5) ±0.3°C 25 0.7°C

Rule of Thumb: If your sensor has noise >1% of full scale or updates faster than the system’s time constant, use PI instead of PID. For a greenhouse (30-minute thermal time constant), sampling every second with ±0.5°C sensor noise makes the derivative term more harmful than helpful.

When PID is Still Worth It:

  • Motor position control (encoder has 0.01% noise, 10ms time constant → D term essential)
  • Precision oven (thermocouple has 0.1°C noise, 5-minute time constant → D term valuable)
  • Flow control (turbine meter has 0.5% noise, 2-second time constant → PI better)

Key Lesson: The derivative term in PID is a noise amplifier. Only use it when (sensor noise / system time constant) <0.1%. Otherwise, PI control provides 90% of PID’s performance with 50% of the complexity and zero noise sensitivity.

71.6 Interactive: Ziegler-Nichols PID Gain Calculator

Enter your ultimate gain (Ku) and oscillation period (Tu) from the Ziegler-Nichols test to calculate starting PID gains.

Key Concepts

  • Proportional Term (P): The PID component producing output proportional to current error: P = Kp × e(t). Increases response speed but cannot eliminate steady-state error alone and risks oscillation at high gain
  • Integral Term (I): The PID component accumulating error over time: I = Ki × ∫e(t)dt. Eliminates steady-state error by continuously increasing output until error reaches zero, but can cause overshoot and integrator windup
  • Derivative Term (D): The PID component responding to rate of error change: D = Kd × de(t)/dt. Provides anticipatory damping that reduces overshoot, but amplifies high-frequency sensor noise requiring derivative filtering
  • Proportional Gain (Kp): The tuning parameter scaling the proportional term — high Kp gives fast response but risks oscillation; low Kp gives stable but slow response with larger steady-state error
  • Integral Gain (Ki): The tuning parameter scaling the integral term — high Ki eliminates steady-state error quickly but causes overshoot and potential windup; low Ki is slow to correct persistent errors
  • Derivative Gain (Kd): The tuning parameter scaling the derivative term — high Kd heavily damps oscillations but amplifies sensor noise; low Kd provides minimal anticipatory action
  • Setpoint: The target value that the PID controller drives the process variable toward — expressed in the same units as the measured process variable (°C for temperature, RPM for speed, mm for position)

Common Pitfalls

Adjusting all three gains at once without a systematic approach. Start with I=0 and D=0, tune Kp for acceptable response, then add Ki to eliminate steady-state error, then add Kd to reduce overshoot. Changing all three simultaneously makes cause-and-effect unclear.

Aggressively increasing Ki to quickly eliminate steady-state error causes integrator windup — the integral term accumulates during output saturation, causing massive overshoot when the output unsaturates. Implement anti-windup clamping and set Ki conservatively.

Applying differentiation to the error signal (setpoint minus measured) causes derivative kick when the setpoint steps — a sudden large setpoint change creates an infinite spike in the derivative term. Apply derivative only to the process variable measurement, not the error.

Implementing a PID controller where Kp is dimensionless but Ki is in 1/seconds and Kd is in seconds, then tuning without tracking units. Dimensional errors cause gains 100× too large or small. Define all units explicitly and verify unit consistency before tuning.

71.7 Summary

In this chapter, we covered the fundamentals of PID control:

Key Takeaways:

  1. PID Components: The three terms (Proportional, Integral, Derivative) each address different aspects of control - current error, accumulated error, and rate of change

  2. Error Calculation: The foundation of PID is the error signal (e = SP - PV), representing the difference between desired and actual values

  3. Proportional Control: Provides immediate response proportional to error magnitude, but cannot eliminate steady-state error

  4. Kp Tuning: Low Kp gives slow response; high Kp gives fast response but risks overshoot and oscillation

  5. P-Only Limitations: Cannot eliminate steady-state error or handle constant disturbances - requires integral term

71.8 What’s Next?

In the next chapter, we’ll explore the Integral and Derivative terms in detail, learning how they address the limitations of proportional-only control.

Continue to Integral and Derivative Control

Previous Current Next
Process Control and PID PID Control Fundamentals Integral and Derivative Control