58  Processes and Systems: PID Control

In 60 Seconds

PID control combines three complementary terms: P (proportional response to current error), I (integral to eliminate steady-state offset), and D (derivative to reduce overshoot). For most IoT applications, PI control suffices – add the D term only when overshoot or oscillation is problematic, as noisy sensor data amplifies derivative kick.

58.1 Learning Objectives

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

  • Explain the purpose and architecture of PID control in IoT feedback systems
  • Differentiate the roles of the Proportional, Integral, and Derivative terms
  • Select the appropriate PID configuration (P, PI, PD, PID) based on application requirements
  • Calculate PID controller output given error, accumulated error, and rate of change values
  • Evaluate real-world IoT control scenarios to determine optimal PID tuning strategies
Minimum Viable Understanding
  • PID control combines three strategies – reacting to current error (P), eliminating accumulated error (I), and anticipating future error (D) – to precisely regulate a process variable like temperature, speed, or position.
  • PI control (Proportional + Integral) handles the vast majority of IoT applications; full PID is only needed when overshoot must be minimized and sensor data is clean.
  • Tuning is the process of setting gain values (Kp, Ki, Kd); conservative gains are safer and more robust than aggressive gains in real-world deployments.

Key Concepts

  • Proportional-Integral-Derivative (PID): The three-term feedback control algorithm where P responds to current error magnitude, I corrects accumulated past error, and D anticipates future error from current rate of change
  • Proportional Band: The range of error values over which the controller output changes from 0% to 100% — proportional band (PB%) = 100% / Kp — wider PB gives more stable but slower response
  • Reset Rate: An alternative way of specifying integral action (repeats per minute) — how many times per minute the integral contribution equals the proportional contribution for a constant error
  • Derivative Rate: The time interval over which the derivative term “predicts” the future error based on current rate of change — typically expressed in seconds (Td)
  • Manual Mode: A PID controller operating state where the operator directly sets the output without feedback control — used during commissioning, maintenance, and emergency override of automatic control
  • Auto Mode: The normal PID operating state where the controller automatically adjusts output to drive process variable toward setpoint based on real-time sensor feedback

58.2 Overview

This section covers PID (Proportional-Integral-Derivative) control, the most widely used feedback control algorithm in industrial and IoT applications. PID controllers enable precise, automated control of processes ranging from temperature regulation to motor speed 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 58.1: PID control system block diagram showing the three parallel control actions working together

Sammy the Sensor says: “Imagine you’re riding a bike and trying to stay in the center of a lane!”

Lila the LED explains the three helpers:

  • P (Proportional) – the Spotter: “You’re drifting 2 feet to the right? Turn left a bit! More drift means a bigger correction.” P reacts to how far off you are right now.
  • I (Integral) – the Memory: “The wind keeps pushing you right every time! I’ll remember that and hold the handlebars a little left all the time.” I remembers past mistakes and fixes repeating problems.
  • D (Derivative) – the Predictor: “Whoa, you’re swinging back too fast! Slow down before you overshoot!” D watches how quickly things are changing and puts on the brakes early.

Max the Microcontroller adds: “In a smart greenhouse, P notices the temperature is too low, I fixes the heater that always runs a bit cold, and D prevents the heater from overshooting when the sun comes out. Together they keep plants perfectly happy!”

Bella the Battery warns: “Running all three takes more computing power, so many IoT devices just use P and I together – that handles most situations just fine!”

PID control is an algorithm that automatically adjusts an output (like a heater, motor, or valve) to keep a measured value (like temperature, speed, or pressure) at a desired target.

Think of it like a thermostat, but much smarter:

  • A basic thermostat just turns heating on or off (bang-bang control)
  • A PID controller smoothly adjusts how much heating to apply, considering:
    • How far the temperature is from the target (Proportional)
    • How long it has been off-target (Integral)
    • How fast the temperature is changing (Derivative)

Why does this matter for IoT? Nearly every IoT system that controls something physical – HVAC, robotic arms, drone stabilization, water treatment, 3D printers – uses some form of PID control. Understanding PID is essential for building systems that respond accurately and stably.

The good news: Most IoT applications only need PI control (two of three terms), which is simpler to understand and tune.

58.3 PID Control Architecture

The following diagram shows how PID control fits within a typical IoT feedback loop:

Flowchart showing the PID control loop in an IoT system: Setpoint enters the error calculator, which computes the difference from the sensor reading. The error feeds into three parallel paths (P, I, D terms) that sum to produce the control output driving the actuator, which affects the physical process measured by the sensor.

58.4 What You’ll Learn

The PID control content is organized into three focused chapters:

58.4.1 Part 1: PID Control Fundamentals

Learn the foundation of PID control:

  • PID Components: Understanding the three terms (P, I, D) and their roles
  • Error Calculation: How setpoint, process variable, and error relate
  • Proportional Control: How P-term responds to current error magnitude
  • P-Only Limitations: Why proportional control alone causes steady-state error
  • PID Equation: The mathematical foundation for controller output

58.4.2 Part 2: Integral and Derivative Control

Master the I and D terms:

  • Integral Control: Eliminating steady-state error through error accumulation
  • Integral Windup: Preventing dangerous over-accumulation
  • Derivative Control: Using rate of change to reduce overshoot
  • PID Configuration Selection: When to use P, PI, PID, or PD
  • Tuning Philosophy: Why conservative gains outperform aggressive tuning

58.4.3 Part 3: PID Implementation and Labs

Hands-on implementation:

  • Arduino/ESP32 Code: Complete PID controller class in C++
  • Lab Exercises: Systematic tuning exploration with P, PI, and PID
  • Python Framework: Production-ready simulation and auto-tuning
  • Performance Metrics: Measuring settling time, overshoot, and error
  • Distributed Control: Edge vs cloud control architecture decisions

58.5 PID Configuration Selection

Choosing the right combination of P, I, and D terms depends on your application requirements:

Decision tree for selecting PID configuration: Start with 'Is steady-state error acceptable?' If yes, use P-only control. If no, ask 'Is sensor data noisy?' If yes, use PI control. If no, ask 'Is overshoot critical?' If yes, use full PID. If no, use PI control. A separate branch shows PD control for fast response systems without steady-state requirements.

58.6 Prerequisites

Before starting this section, you should understand:

  • Basic feedback control concepts (open-loop vs closed-loop)
  • Process variables, setpoints, and error signals
  • Simple programming concepts (variables, loops, functions)

58.7 Learning Path

Table 58.1: PID Control Learning Path
Chapter Focus Difficulty Time
PID Fundamentals Theory & P-term Intermediate 25 min
Integral & Derivative I & D terms Intermediate 30 min
Implementation Code & Labs Advanced 45 min

58.8 How the Three Terms Work Together

The following diagram illustrates the distinct role each PID term plays and when each is most active during a control response:

Timeline diagram showing how P, I, and D terms contribute during a step response: D term is most active at the start when error changes rapidly, P term dominates during the transient phase proportional to error magnitude, and I term builds gradually to eliminate the remaining steady-state error over time.

58.9 Quick Reference

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 (e.g., heater power, motor voltage)
  • \(e(t)\) = error = setpoint - measured value
  • \(K_p\) = proportional gain (responsiveness)
  • \(K_i\) = integral gain (steady-state correction)
  • \(K_d\) = derivative gain (overshoot dampening)

Common Configurations:

Mode When to Use IoT Example
P Simple systems, some error acceptable LED brightness dimming
PI Most common, general-purpose control HVAC temperature regulation
PID High-performance, minimal overshoot needed Drone altitude hold
PD Fast servos without steady-state concerns Robotic arm positioning

58.10 IoT PID Application Map

Mind map showing PID control applications across IoT domains: Smart Home (HVAC, lighting), Industrial IoT (motor control, flow regulation, pressure), Agriculture (irrigation, greenhouse climate), Robotics (drone stabilization, arm control), and Smart Grid (battery charging, power regulation).

58.11 Interactive: Greenhouse PI Control Snapshot

Replicate the worked example calculation. Enter temperature and accumulated error to see the PI controller output.

58.12 Worked Example: Smart Greenhouse Temperature Control

Worked Example: Choosing and Configuring PID for a Smart Greenhouse

Scenario: You are building an IoT-controlled greenhouse that must maintain the temperature at 24 degrees C (plus or minus 0.5 degrees C). The system uses a DHT22 temperature sensor (accuracy plus or minus 0.5 degrees C, reads every 2 seconds) and controls a 2 kW heater via a PWM-driven relay. Outdoor temperature varies between 5 and 15 degrees C depending on the season.

Step 1: Choose the PID Configuration

  • Steady-state error acceptable? No – plants need consistent temperature.
  • Sensor data noisy? Moderately – DHT22 has plus or minus 0.5 degrees C accuracy, and readings can fluctuate.
  • Overshoot critical? Somewhat – large overshoots could stress plants, but a brief 1 to 2 degrees C overshoot is tolerable.

Decision: PI control is the best fit. The D term would amplify sensor noise without significant benefit for this thermal system (which has slow dynamics).

Step 2: Define the Parameters

  • Setpoint: 24.0 degrees C
  • Sampling interval: 2 seconds (matching DHT22 read rate)
  • Output range: 0 to 100% PWM duty cycle for the heater

Step 3: Initial Tuning (Ziegler-Nichols-inspired)

  1. Start with PI: set \(K_p = 10\), \(K_i = 0.1\), \(K_d = 0\)
  2. Observe response: if temperature overshoots by more than 2 degrees C, reduce \(K_p\) to 7
  3. If steady-state offset remains after 10 minutes, increase \(K_i\) to 0.2
  4. Add integral windup limit: cap accumulated error at plus or minus 50 (prevents runaway heating)

Step 4: Calculate Controller Output (example snapshot)

At time \(t\), sensor reads 22.0 degrees C:

  • Error: \(e(t) = 24.0 - 22.0 = 2.0\) degrees C
  • Accumulated error over last 60 seconds: \(\sum e = 45.0\) degree-seconds
  • Controller output: \(u(t) = 10 \times 2.0 + 0.1 \times 45.0 = 20.0 + 4.5 = 24.5\%\) PWM

The heater runs at 24.5% power. As temperature approaches the setpoint, P-term decreases. If a persistent 0.3 degrees C offset remains, the I-term gradually increases output to close the gap.

Result: Temperature stabilizes at 24.0 plus or minus 0.3 degrees C within 15 minutes, well within the required tolerance for plant growth.

Tracking PI controller output as the greenhouse warms (K_p=10, K_i=0.1, sampling every 2s):

t=0s: Temp=20°C → \(e=4.0\)°C, \(\sum e = 0\)\(u = 10(4.0) + 0.1(0) = 40\)% PWM t=60s: Temp=22°C → \(e=2.0\)°C, \(\sum e = 45\) °C·s → \(u = 10(2.0) + 0.1(45) = 24.5\)% t=120s: Temp=23.5°C → \(e=0.5\)°C, \(\sum e = 60\) °C·s → \(u = 10(0.5) + 0.1(60) = 11\)% t=180s: Temp=24.3°C → \(e=-0.3\)°C, \(\sum e = 55\) °C·s → \(u = 10(-0.3) + 0.1(55) = 2.5\)%

Notice how the I-term keeps growing (0 → 4.5 → 6.0 → 5.5) even as P-term shrinks (40 → 20 → 5 → -3). When temp overshoots to 24.3°C, negative P-term reduces output, but accumulated I-term (5.5%) prevents heater from shutting off completely, avoiding oscillation.

58.13 Common Pitfalls

Common Mistake: Running Fast Control Loops in the Cloud

The Mistake: A team building a robotic arm for warehouse automation implements PID motor control in the cloud. The position sensor (encoder) sends readings to AWS Lambda, which computes PID output and sends motor commands back to the device. In testing, the arm oscillates wildly and cannot hold a stable position.

Why It Fails:

Network latency breakdown:

  • Sensor reading to AWS: 80-150 ms (cellular uplink)
  • Lambda cold start: 0-500 ms (first invocation)
  • Lambda compute: 20-50 ms
  • Command back to device: 80-150 ms (downlink)
  • Total round-trip latency: 200-850 ms (average 400 ms)

Motor control time constant: 50-100 ms (the time for motor to respond to a step input)

Stability requirement: Control loop frequency must be 10x faster than process time constant. For a 100 ms motor, you need a 10 ms control loop. The 400 ms cloud latency is 40x too slow.

What happens:

  1. At t = 0 ms: Arm at position 0°, target 90°, error = 90°
  2. PID calculation happens in cloud (400 ms later at t = 400 ms)
  3. Motor receives command at t = 400 ms, starts moving
  4. At t = 450 ms: Arm reaches 90° but continues due to momentum
  5. Next sensor reading reaches cloud at t = 850 ms showing position 110° (20° overshoot)
  6. Cloud calculates reverse command, arrives at device at t = 1250 ms
  7. Arm has now overshot to 130° due to outdated command
  8. System oscillates with increasing amplitude (unstable)

Performance metrics:

Metric Cloud Control Edge Control Impact
Control loop frequency 2.5 Hz (400 ms) 100 Hz (10 ms) 40x faster
Position error (RMS) ± 15° oscillation ± 0.5° steady 30x more accurate
Settling time Never settles (unstable) 200 ms Infinite improvement
Network data usage 100 KB/sec (position + commands) 1 KB/sec (logs only) 100x reduction
Works offline? No (requires internet) Yes (autonomous) Critical for reliability

The Correct Approach: Edge Control with Cloud Supervision

Architecture:

  1. Edge controller (ESP32): Runs PID loop at 100 Hz, reads encoder, controls motor locally
  2. Cloud (AWS): Receives position logs every 5 seconds for monitoring, sends high-level commands (“move to position 90°”) that update edge controller setpoints
  3. Result: 200 ms settling time, ± 0.5° accuracy, works during internet outages

Code split:

// EDGE (ESP32) - 100 Hz PID control loop
void loop() {
    static unsigned long last_time = 0;
    if (millis() - last_time >= 10) { // 10 ms = 100 Hz
        float position = read_encoder();
        float error = setpoint - position;
        float pid_output = compute_pid(error); // Local PID calculation
        set_motor_pwm(pid_output);

        last_time = millis();
    }

    // Send telemetry to cloud every 5 seconds (low frequency)
    if (millis() % 5000 == 0) {
        send_mqtt("position", position);
    }
}
# CLOUD (AWS Lambda) - Supervisory control only
def lambda_handler(event, context):
    # Receive high-level command from user
    new_target = event['target_position']

    # Send setpoint update to edge (NOT real-time control)
    mqtt_client.publish("device/setpoint", new_target)

    # Log for analytics
    db.insert("commands", {"target": new_target, "timestamp": time.now()})

When to use edge vs cloud control:

Process Time Constant Control Location Rationale
< 1 second (motors, power electronics) Edge only Cloud latency exceeds process dynamics → instability
1-10 seconds (liquid flow, small heaters) Edge (cloud for setpoints) Edge provides fast response, cloud optimizes strategy
10-60 seconds (room temperature, pressure) Edge or cloud Both viable; edge preferred for offline resilience
> 60 seconds (greenhouse, large tanks) Cloud acceptable Slow dynamics tolerate network latency

Key lesson: Control loop frequency must match process dynamics. Fast processes (motors, drones, anything mechanical) require edge control with sub-100 ms latency. Cloud is for slow processes (HVAC, irrigation) or supervisory functions (setpoint optimization, analytics, alerts). Mixing these responsibilities leads to instability and poor performance.

Additional Common PID Control Pitfalls in IoT Systems

1. Integral Windup When the actuator reaches its physical limit (e.g., heater at 100%), the I-term keeps accumulating error. When the setpoint is reached, the built-up integral causes massive overshoot. Fix: Always implement integral windup clamping (cap the accumulated error).

2. Derivative Kick on Noisy Sensors The D-term amplifies high-frequency noise from sensors like accelerometers or low-cost temperature sensors, causing erratic actuator behavior. Fix: Use PI-only control for noisy sensors, or apply a low-pass filter before the D-term.

3. Wrong Sampling Rate Sampling too fast wastes power and amplifies noise; sampling too slow misses important dynamics and causes instability. Fix: Sample at least 10 times faster than the process time constant (e.g., for a thermal system with a 5-minute time constant, sample at least every 30 seconds).

4. Aggressive Tuning in Production Gains tuned in a lab often fail in the field due to environmental variation (wind, load changes, aging components). Fix: Start with conservative gains (50% of calculated optimal) and increase gradually during field testing.

5. Ignoring Actuator Limits PID math can output values outside the physical range (negative power, or 200% speed). Sending out-of-range commands can damage hardware. Fix: Always clamp the final output to the actuator’s valid operating range (e.g., 0 to 100%).

58.14 Knowledge Checks

Test your understanding of PID control concepts:

58.15 Summary

PID control is the backbone of automated process control in IoT systems. Here are the key takeaways:

Concept Key Point
PID Purpose Automatically adjusts actuator output to maintain a process variable at a desired setpoint
P (Proportional) Responds to current error magnitude – larger error produces larger correction
I (Integral) Eliminates steady-state error by accumulating past errors over time
D (Derivative) Reduces overshoot by responding to the rate of error change
Most Common Config PI control handles 80%+ of IoT applications; full PID only when overshoot is critical and sensors are clean
Critical Pitfall Integral windup – always implement anti-windup clamping when using the I-term
Edge vs. Cloud Run PID on edge for fast processes (under 1 second); cloud for supervisory setpoint adjustment only
Tuning Philosophy Start conservative (50% of optimal gains), increase gradually in field conditions

58.16 What’s Next

If you want to… Read this
Study PID system fundamentals in depth PID Control Fundamentals
Learn about integral and derivative terms Integral and Derivative Control
Explore PID implementation details PID Implementation and Labs
Study PID tuning and applications PID Tuning and Applications
Practice with the simulation lab PID Simulation Lab