62 Processes & Systems: PID Control
62.1 Learning Objectives
By the end of this chapter, you will be able to:
- Explain the roles of proportional, integral, and derivative control components in the PID algorithm
- Calculate PID controller output given error, accumulated integral, and rate of change values
- Tune PID gain values (Kp, Ki, Kd) using systematic methods for stable system performance
- Implement PID control algorithms in firmware for real IoT devices (ESP32, Arduino)
- Select the appropriate PID configuration (P, PI, PD, PID) based on system dynamics and sensor quality
62.2 Prerequisites
Before diving into this chapter, you should be familiar with:
- Processes & Systems: Core Definitions: Understanding system decomposition and input-output transformations
- Processes & Systems: Control Types: Open-loop vs closed-loop control and feedback mechanisms
- Sensor Fundamentals and Types: How sensors measure physical phenomena for feedback
- Actuators: How actuators produce physical outputs in response to control signals
62.3 Getting Started (For Beginners)
What is PID Control? (Simple Explanation)
Analogy: PID control is like driving a car to a target speed:
- P (Proportional): The farther you are from target speed, the harder you press the gas
- I (Integral): If you’ve been slow for a while, press harder to catch up
- D (Derivative): If you’re approaching target fast, ease off to avoid overshooting
Combined: P + I + D = smooth, accurate approach to your target!
Key Takeaway
In one sentence: PID combines three control actions—react to current error (P), eliminate persistent offset (I), and dampen oscillations (D)—to maintain precise setpoint control.
Remember this: Most real-world control systems (thermostats, drones, cruise control) use PID because it handles disturbances and changes automatically.
62.4 PID Control Basics for IoT
⭐⭐ Difficulty: Intermediate
Proportional-Integral-Derivative (PID) control is the most widely used feedback control algorithm in industrial automation and IoT systems. It combines three control actions to maintain a system at its desired setpoint.
62.4.1 The PID Formula
The PID controller calculates the control output \(u(t)\) based on the error \(e(t)\) between the setpoint and the measured value:
\[ u(t) = K_p \cdot e(t) + K_i \cdot \int_0^t e(\tau) \, d\tau + K_d \cdot \frac{de(t)}{dt} \]
Putting Numbers to It
Temperature control example with Kp=15, Ki=0.5, Kd=5:
At t=60s: setpoint 22°C, measured 18.5°C, previous error (at t=59s) was 3.8°C, accumulated integral = 12.3°C·s
Calculate each term:
Error: \(e(t) = 22 - 18.5 = 3.5°C\)
P-term: \(K_p e(t) = 15 \times 3.5 = 52.5\%\) power
I-term: \(K_i \int_0^t e(\tau) d\tau = 0.5 \times 12.3 = 6.15\%\) power
D-term: \(K_d \frac{de}{dt} = 5 \times \frac{3.5 - 3.8}{1} = 5 \times (-0.3) = -1.5\%\) power (braking)
Total output: \(u(t) = 52.5 + 6.15 - 1.5 = 57.15\%\) heater duty cycle
The negative D-term reduces output because temperature is approaching setpoint (error decreasing), preventing overshoot.
Interactive PID Output Calculator:
Where: - \(u(t)\): Control output (e.g., valve position, motor speed, heater power) - \(e(t) = \text{setpoint} - \text{measured value}\): Current error - \(K_p\): Proportional gain (how strongly to react to current error) - \(K_i\): Integral gain (how strongly to correct accumulated past errors) - \(K_d\): Derivative gain (how strongly to react to error rate of change)
62.4.2 The Three Control Actions
1. Proportional (P) - React to Current Error:
- What it does: Output is proportional to the current error magnitude
- Effect: Larger error → stronger correction
- Problem: Never quite reaches setpoint (steady-state error)
- Analogy: Pushing harder on accelerator the farther you are from target speed
Example: Smart thermostat with P-only control: - Current temp: 18°C, Setpoint: 22°C → Error: 4°C - Control output: \(u = K_p \times 4\) (e.g., if \(K_p = 15\), then \(u = 60\%\) heater power) - As room warms to 21°C, error drops to 1°C → \(u = 15\%\) heater power - Problem: At 21.7°C, heater power equals heat loss → stuck below setpoint!
2. Integral (I) - Account for Accumulated Error:
- What it does: Accumulates error over time and corrects for persistent offset
- Effect: Eliminates steady-state error (eventually reaches exact setpoint)
- Problem: Can cause overshoot and slow oscillations if too aggressive
- Analogy: Remembering that you’ve been consistently behind schedule and compensating
Example: Adding I-control to thermostat: - Even when temp hovers at 21.7°C (error = 0.3°C), integral term keeps growing - \(\int e(t) dt\) accumulates: 0.3 + 0.3 + 0.3… over many time steps - Eventually integral term adds enough output to push temp to exactly 22°C - Benefit: Reaches exact setpoint, not just “close enough”
3. Derivative (D) - Predict Future Error:
- What it does: Responds to rate of change of error (how fast it’s changing)
- Effect: Dampens oscillations, improves stability, slows overshoot
- Problem: Amplifies sensor noise (small noise fluctuations look like large rate changes)
- Analogy: Seeing you’re approaching target speed quickly and easing off accelerator early
Example: Adding D-control to thermostat: - Temp rising rapidly from 18°C → 19°C → 20°C (1°C per minute) - \(de/dt = -1°C/\text{min}\) (error decreasing at 1°C/min) - D-term reduces output before reaching setpoint: “We’re getting there fast—slow down!” - Benefit: Less overshoot, smoother approach to setpoint
62.4.3 Tuning PID Controllers
Finding the right \(K_p\), \(K_i\), \(K_d\) values is critical:
| Parameter | Too Low | Optimal | Too High |
|---|---|---|---|
| \(K_p\) (Proportional) | Slow response, large steady-state error | Fast response, minimal overshoot | Overshoot, oscillations, instability |
| \(K_i\) (Integral) | Persistent offset, never reaches setpoint | Eliminates offset, stable | Large overshoot, slow oscillations |
| \(K_d\) (Derivative) | Overshoot, oscillations | Smooth approach, damped response | Noise amplification, erratic behavior |
Common Tuning Methods:
- Ziegler-Nichols Method: Empirical tuning based on step response
- Manual Tuning: Start with P-only, add I to eliminate offset, add D to reduce overshoot
- Auto-Tuning: Modern controllers can self-tune by observing system response
62.5 Real IoT PID Control Examples
62.5.1 Example 1: Smart Thermostat (Temperature Control)
System Components:
| Component | Details | IoT Integration |
|---|---|---|
| Setpoint | Desired temperature: 22°C | Set via smartphone app or voice assistant |
| Sensor | DHT22 temperature sensor (±0.5°C) | I2C interface to ESP32 microcontroller |
| Controller | PID algorithm (\(K_p=15\), \(K_i=0.5\), \(K_d=5\)) | Runs every 30 seconds on ESP32 |
| Actuator | Smart relay controlling HVAC system | 240V relay switched by GPIO pin |
| Process | Room thermal dynamics (5-10 min time constant) | Cloud logging of temperature history |
Operation:
1. Measure: Sensor reads 18.5°C
2. Error: 22.0 - 18.5 = 3.5°C
3. P-term: 15 × 3.5 = 52.5
4. I-term: 0.5 × Σ(errors) = 0.5 × 12.3 = 6.15 (accumulated over past 5 minutes)
5. D-term: 5 × (3.5 - 3.8)/30s = -0.05 (error decreasing slowly)
6. Output: 52.5 + 6.15 - 0.05 = 58.6% heater duty cycle
7. Actuate: HVAC runs at 58.6% power for next 30 seconds
8. Repeat: Measure again after 30 seconds
Results:
- Settling Time: 8 minutes to reach 22°C ±0.2°C
- Overshoot: <0.3°C (minimal temperature overshoot)
- Energy Savings: 23% reduction vs simple on/off thermostat
- Comfort: ±0.2°C stability vs ±1.5°C with on/off control
62.5.2 Example 2: Drone Stability (Orientation Control)
System Components:
| Component | Details | Update Rate |
|---|---|---|
| Setpoint | Target orientation: level (0° pitch, 0° roll) | User joystick commands |
| Sensor | MPU-6050 IMU (gyroscope + accelerometer) | 100 Hz (every 10ms) |
| Controller | Cascaded PID loops (angle PID → rate PID) | 400 Hz (every 2.5ms) |
| Actuator | 4× brushless motors with ESCs | PWM 1000-2000µs pulse width |
| Process | Quadcopter rotational dynamics | <50ms response time |
Dual-Loop Control (Cascaded PID):
Outer Loop (Angle Control):
- Setpoint: 0° pitch (level flight)
- Measured: Accelerometer reads 5° nose-down pitch
- Error: 0° - 5° = -5°
- PID Output: Desired pitch rate = +30°/sec (rotate nose up)
Inner Loop (Rate Control):
- Setpoint: +30°/sec (from outer loop)
- Measured: Gyroscope reads +10°/sec (rotating up, but too slowly)
- Error: +30°/sec - 10°/sec = +20°/sec
- PID Output: Increase rear motors by 15%, decrease front motors by 15%
- Result: Drone pitches nose up at 30°/sec → returns to level
Why Two Loops?
- Outer loop (slow): Strategic goal—“Get to level orientation”
- Inner loop (fast): Tactical execution—“Rotate at this exact rate”
- Benefit: Faster response, better stability than single-loop control
62.5.3 Example 3: Water Tank Level Control
System Setup:
| Component | Specification | Purpose |
|---|---|---|
| Setpoint | 75% tank level | Maintain optimal water supply |
| Sensor | Ultrasonic distance sensor (HC-SR04, ±3mm) | Measure water level every 5 seconds |
| Controller | Arduino Uno running PID library | Calculate pump speed (0-100%) |
| Actuator | Variable speed pump (0-50 liters/min) | Controlled via PWM to motor driver |
| Process | 1000-liter water tank (60cm × 60cm × 278cm) | 5-minute time constant |
Control Challenges:
- Disturbances: Water consumption varies (0-30 L/min depending on household usage)
- Nonlinearity: Pump efficiency changes with tank level (less efficient at low levels)
- Noise: Ultrasonic sensor has ±3mm noise (~0.3% of tank height)
PID Solution (\(K_p=20\), \(K_i=0.8\), \(K_d=8\)):
Scenario: Heavy water usage (shower + dishwasher)
1. Tank drops: 75% → 70% → 65% in 2 minutes
2. Error grows: 10% below setpoint
3. P-term: 20 × 10 = 200 → pump at 100% (capped at max speed)
4. I-term accumulates: 0.8 × Σ(errors) = keeps pump running even as level recovers
5. D-term: Sees rapid level drop (de/dt large) → boosts pump early
6. Result: Tank refills to 75% in 8 minutes, stabilizes with ±1% fluctuation
Performance Metrics:
| Metric | Without PID (On/Off Control) | With PID Control |
|---|---|---|
| Level Stability | ±8% variation | ±1% variation |
| Pump Starts/Hour | 12 starts (wear and energy spikes) | 2-3 starts (soft start via PWM) |
| Water Shortage Events | 3 per month (tank empty) | 0 per year |
| Energy Consumption | 2.8 kWh/day (frequent on/off) | 2.1 kWh/day (smooth operation) |
| Pump Lifespan | ~3 years (mechanical stress) | ~7 years (gentle operation) |
62.6 When to Use PID vs Simpler Control
Not every IoT system needs PID control. Here’s a decision framework:
| Scenario | Control Strategy | Reasoning |
|---|---|---|
| Simple on/off (LED, valve) | Bang-bang (on/off) control | No proportional control needed—device is either on or off |
| Slow process, low precision (room temp ±2°C OK) | Simple thermostat (on when cold, off when hot) | Thermal inertia provides natural smoothing |
| Fast process, high precision (drone, motor) | PID required | Must respond quickly and accurately to avoid instability |
| Multiple interacting variables (HVAC: temp + humidity) | Multi-loop PID or advanced control | Single-variable PID insufficient for coupled systems |
| Highly nonlinear (battery charging) | Look-up table + PID trim | PID struggles with extreme nonlinearity—hybrid approach better |
| Safety-critical (medical, automotive) | PID + redundancy + fault detection | Reliability and failsafes essential |
Rule of Thumb:
- Bang-bang control: Simple, cheap, acceptable performance (±10% tolerance)
- PID control: Moderate complexity, better performance (±1-2% tolerance)
- Advanced control (MPC, adaptive): High complexity, optimal performance (<±0.5% tolerance)
IoT-Specific Considerations:
- Computational Resources: PID requires floating-point math—ensure MCU can handle it at required sample rate
- Sensor Quality: Noisy sensors → add filtering before PID or reduce derivative gain
- Communication Latency: If control loop spans cloud (sensor → cloud → actuator), latency may prevent effective PID → use edge computing
- Energy Constraints: Continuous PID sensing/actuation consumes power → consider duty-cycled control for battery devices
Cross-Hub Connections
Interactive Learning Tools:
- Simulations Hub - Try the PID Tuner Simulator to see how changing Kp, Ki, Kd affects system response
- Videos Hub - Watch PID control demonstrations showing real controllers, tuning methods, and system stability
- Quizzes Hub - Test your understanding of PID components, tuning, and control strategy selection
Knowledge Resources:
- Knowledge Gaps Hub - Common misconceptions about PID tuning and stability explained
- Knowledge Map - See how PID control connects to sensors, actuators, and system design
Related Chapters
This Series:
- Processes & Systems: Core Definitions - What are processes and systems
- Processes & Systems: Control Types - Open-loop vs closed-loop control
Deep Dives:
- Process Control and PID - Advanced feedback control systems
- Processes Labs and Review - Hands-on implementations
- PID Feedback Fundamentals - Mathematical foundations
Foundation:
- IoT Reference Models - System architecture layers
- State Machines in IoT - Control state management
Sensing & Actuation:
- Sensor Fundamentals - Input devices
- Actuators - Output devices
- Sensor Circuits - Interfacing
Design:
- Energy Management - Power optimization
- Hardware Prototyping - System building
62.7 Visual Reference Gallery
Visual: Coffee Pot Control System Block Diagram
This visualization illustrates the fundamental closed-loop control concepts using a familiar household appliance, demonstrating how sensors, controllers, and actuators work together.
Visual: Closed-Loop Feedback System
This diagram shows the general architecture of closed-loop feedback systems fundamental to understanding PID control and IoT process automation.
Visual: Adding Integral Control Action
This figure demonstrates how integral control eliminates steady-state error by integrating accumulated error over time, a key concept in PID controller design.
Worked Example: Tuning PID for Industrial Water Tank Level Control
Scenario: A chemical processing plant uses a 10,000-liter water tank to supply cooling water. The tank must maintain 75% level (7,500 liters) despite variable consumption from 0-200 L/min. Design and tune a PID controller for the inlet pump (0-300 L/min variable speed).
System Characterization:
- Tank dimensions: 2m diameter × 3.2m height
- Inlet pump: Variable speed, 0-300 L/min
- Outlet flow: Variable, 0-200 L/min (process consumption)
- Level sensor: Ultrasonic, ±5mm accuracy, updates every 1 second
- System time constant: ~5 minutes (time for 50% level change at 100 L/min net flow)
Step 1: Open-Loop Test (Determine System Dynamics)
Start at 50% level, apply step input (pump at 150 L/min with 0 consumption): - T=0s: Level 50% (5,000 L) - T=60s: Level 53% (5,300 L) → 300L added = 150 L/min ✓ - T=180s: Level 59% (5,900 L) - T=300s: Level 65% (6,500 L) → 1,500L added in 5 min = 300 L/min net
Measure response curve: - Rise time to 90%: ~12 minutes - Settling time: ~18 minutes - No overshoot (open-loop)
Step 2: Ziegler-Nichols Tuning Method
Set Ki=0, Kd=0, increase Kp until sustained oscillation: - Kp=0.5: Slow approach, no oscillation - Kp=2.0: Approaches setpoint, minor overshoot - Kp=5.0: Oscillates! ±3% around setpoint, period Tu=120 seconds - Critical gain Ku = 5.0, Period Tu = 120 seconds
Calculate PID gains (Ziegler-Nichols table): - Kp = 0.6 × Ku = 0.6 × 5.0 = 3.0 - Ki = 2 × Kp / Tu = 2 × 3.0 / 120 = 0.05 - Kd = Kp × Tu / 8 = 3.0 × 120 / 8 = 45.0
Step 3: Real-World Test with Calculated Gains
Apply PID(3.0, 0.05, 45.0) with disturbance (consumption jumps from 0 to 150 L/min at T=300s):
| Time | Setpoint | Actual Level | Error | P | I | D | Pump Output |
|---|---|---|---|---|---|---|---|
| T=0s | 75% | 60% | +15% | 45.0 | 0 | 0 | 300 L/min (max) |
| T=60s | 75% | 64% | +11% | 33.0 | 3.0 | -1.8 | 275 L/min |
| T=120s | 75% | 68% | +7% | 21.0 | 5.5 | -1.8 | 224 L/min |
| T=180s | 75% | 72% | +3% | 9.0 | 7.0 | -1.8 | 165 L/min |
| T=240s | 75% | 74.5% | +0.5% | 1.5 | 7.5 | -1.1 | 158 L/min |
| T=300s | 75% | 75.0% | 0% | 0 | 7.5 | -0.2 | 157 L/min |
| T=300s | Disturbance: consumption → 150 L/min | ||||||
| T=310s | 75% | 74.2% | +0.8% | 2.4 | 7.9 | +3.6 | 213 L/min |
| T=360s | 75% | 74.8% | +0.2% | 0.6 | 8.1 | +0.3 | 158 L/min |
Performance Metrics:
- Rise time: 240 seconds (4 min) to reach 99% of setpoint
- Overshoot: 0.2% (negligible)
- Settling time: 270 seconds (4.5 min) to stay within ±1%
- Steady-state error: 0% (integral action eliminates)
- Disturbance rejection: Returned to setpoint in 60 seconds
Step 4: Fine-Tuning for Production
The Ziegler-Nichols gains were slightly aggressive. Reduce for smoother operation: - Kp = 2.5 (reduce 17% for less aggressive response) - Ki = 0.05 (keep—needed for zero steady-state error) - Kd = 40.0 (reduce 11% to avoid amplifying sensor noise)
Final Performance:
- Settling time: 330 seconds (5.5 min) ← 20% slower but smoother
- Overshoot: 0% ← eliminated
- Steady-state error: 0%
- Pump wear: 60% less cycling (important for 10-year pump lifespan)
Key Insight: Ziegler-Nichols provides a starting point, not the final answer. Production tuning prioritizes actuator lifespan (reducing pump cycling) over minimal settling time. The 20% slower response (330s vs 270s) is acceptable given the 5-minute system time constant, and the reduced cycling extends pump life from 5 years to 10+ years.
Decision Framework: Selecting P, PI, PID, or PD Configuration
Decision Table:
| System Characteristic | Recommended Controller | Reasoning |
|---|---|---|
| Simple position control (servo, valve) | P-only (Kp=1-10, Ki=0, Kd=0) | Fast response, acceptable steady-state error (±2%) |
| Temperature control (HVAC, oven) | PI (Kp=2-10, Ki=0.1-1.0, Kd=0) | Eliminates offset, no D needed (slow thermal dynamics) |
| High-inertia systems (large motors, tanks) | PID (Kp, Ki, Kd all active) | D term prevents overshoot from momentum |
| Noisy sensors (ultrasonic, low-res ADC) | PI (skip D) | D amplifies noise; use moving average filter + PI |
| Fast systems (drones, robotics) | PID with rate limits | D essential for stability, but clamp dD/dt to prevent spikes |
| Battery-powered devices | P-only or PI | D requires fast sampling (power-hungry); P/PI work at 1-10 sec intervals |
PID Term Usage Statistics (Industry Survey):
- P-only: 20% (simple positioning, non-critical)
- PI: 65% (most common—HVAC, process control, industrial)
- PID: 10% (high-performance—robotics, aerospace)
- PD: 5% (rare—specific cases where integral causes issues)
Quick Selection Guide:
Start with P-only: Set Ki=0, Kd=0. Increase Kp until system responds quickly but oscillates slightly. Reduce Kp by 20%. If steady-state error >5%, proceed to step 2.
Add I (→ PI controller): Set Ki = Kp / (10 × settling time). If overshoot >10% or oscillations develop, reduce Ki by 50%. If steady-state error eliminated and overshoot <5%, stop here (PI is sufficient). If overshoot >10%, proceed to step 3.
Add D (→ PID controller): Set Kd = Kp × (settling time / 10). If output becomes erratic, reduce Kd or add low-pass filter to sensor input (cutoff = 1/(10 × sample period)).
Real-World Example Mapping:
- Smart thermostat (DHT22, 2-second samples) → PI (Kp=5.0, Ki=0.2, Kd=0)
- Quadcopter (IMU, 400 Hz samples) → PID (Kp=1.5, Ki=0.3, Kd=0.8)
- Water tank (ultrasonic, 1-second samples) → PI (Kp=3.0, Ki=0.05, Kd=0)
- LED dimmer (potentiometer, 10-second samples) → P-only (Kp=2.0, Ki=0, Kd=0)
Common Mistake: Tuning PID Gains on a Desk Instead of in the Field
The Mistake: Engineers tune PID parameters using a development prototype on a lab bench with controlled conditions, then deploy to production where environmental factors (temperature swings, voltage variations, mechanical wear) cause the controller to become unstable or sluggish.
Real Example: A team developed a smart aquarium heater, tuning PID gains to maintain 25°C ±0.1°C with a 50-liter test tank in a climate-controlled lab (22°C room). Production deployment to customer homes: - Customer A: Cold basement (12°C), 50L tank → System overshoots to 28°C (tuned for 22°C ambient) - Customer B: Sunny window (28°C), 200L tank → Takes 45 minutes to reach setpoint (tuned for 50L thermal mass) - Customer C: Older heater (240V ±10% variation) → Oscillates ±1.5°C (tuned for stable lab power)
Why It Happens:
- Gain Scheduling Needed: Optimal PID gains change with operating point. Kp=5.0 works at 25°C but causes overshoot at 30°C (heater output nonlinear with temperature difference).
- System Identification Incomplete: Lab testing didn’t capture real-world variability (tank sizes, ambient temps, heater aging).
- No Adaptive Tuning: Fixed gains can’t handle 200L vs 50L thermal mass (4× difference → settling time changes).
The Fix:
Solution 1: Gain Scheduling (Manual)
// Adjust gains based on error magnitude
if (abs(error) > 5.0) {
// Far from setpoint: aggressive
Kp = 8.0; Ki = 0.5; Kd = 2.0;
} else if (abs(error) > 1.0) {
// Near setpoint: moderate
Kp = 5.0; Ki = 0.3; Kd = 1.5;
} else {
// At setpoint: gentle
Kp = 2.0; Ki = 0.1; Kd = 0.5;
}Solution 2: Adaptive Tuning (Auto-Commissioning)
- On first power-up, run system identification: Apply step input, measure time constant and gain
- Calculate appropriate PID gains for detected system (e.g., large tank → reduce Kp, increase Ki)
- Store in EEPROM, recalibrate every 6 months
Solution 3: Field Testing Checklist Before production release, test with: - [ ] Min/max tank sizes (customer spec ±50%) - [ ] Min/max ambient temperatures (0°C to 40°C) - [ ] Voltage variations (230V ±10% for EU, 120V ±10% for US) - [ ] Aged components (simulate with 80% heater power) - [ ] Sensor noise (add ±0.3°C random noise to readings)
Key Lesson: If your system operates in variable environments, either implement adaptive tuning or provide multiple pre-tuned profiles (small tank / large tank / cold room / warm room) that users can select during setup.
Key Concepts
- PID Algorithm: The digital control formula: u[n] = Kp×e[n] + Ki×Ts×Σe[k] + Kd/Ts×(e[n]-e[n-1]) where Ts is sample time, Kp/Ki/Kd are gains, and e[n] is current error — each term independently adjustable
- Proportional Band: The error range over which the output changes from 0% to 100% — PB% = 100/Kp — wider band gives more stable but slower response; often the preferred unit in process industry DCS systems
- Integral Windup: Unbounded growth of the integral term during actuator saturation, causing large overshoot when the actuator unsaturates — prevented by integral clamping, conditional integration, or back-calculation anti-windup
- Derivative Filter: A low-pass filter applied to the derivative input (process variable measurement) to attenuate high-frequency sensor noise before differentiation amplifies it into large control output spikes
- Sampling Theorem: The Nyquist criterion requiring PID sample rate ≥ 2× control bandwidth — in practice, sample at 5–20× the desired bandwidth to ensure Kd and Ki behave as designed
- Control Output Range: The physical limits of the actuator (0–100% valve position, 0–255 PWM count) that constrain the controller output, requiring clamping to prevent impossible commands reaching the actuator
Common Pitfalls
1. Implementing PID Without Fixed Sample Time
Running PID in a polling loop with variable execution time. Ki and Kd depend on sample period Ts — variable Ts means gains change randomly between iterations. Use hardware timer interrupts to ensure consistent Ts for correct integral and derivative behavior.
2. Not Implementing Anti-Windup Before Enabling Integral
Adding integral action to a control loop without anti-windup protection. When the actuator saturates during startup or large setpoint changes, the integral accumulates unboundedly. When the actuator exits saturation, massive overshoot occurs. Always implement anti-windup before enabling integral action.
3. Using Derivative on the Error Instead of the Process Variable
Differentiating the error signal (setpoint minus measurement) rather than just the measurement. When the setpoint steps, the error steps too, creating an impulse in the derivative term that drives the actuator to saturation. Differentiate only the process variable measurement.
4. Scaling PID Gains Incorrectly for Engineering Units
Implementing PID where error is in millivolts but the control output is in percent (0–100). Without proper scaling, Kp computed from system analysis in physical units does not transfer to the implementation. Define all units and scaling factors explicitly before coding.
62.8 Summary
This chapter covered PID control theory and applications for IoT:
- PID Control Theory: Learning the three control actions—Proportional (react to current error), Integral (eliminate accumulated error), and Derivative (predict and dampen oscillations)
- The PID Formula: Understanding the mathematical relationship \(u(t) = K_p \cdot e(t) + K_i \cdot \int e(\tau) d\tau + K_d \cdot \frac{de}{dt}\)
- PID Tuning: Finding optimal gain values (\(K_p\), \(K_i\), \(K_d\)) to balance response speed, stability, and precision
- Real-World PID Applications: Implementing feedback control in smart thermostats (temperature regulation), drones (orientation stability), and water tanks (level control)
- Cascaded Control: Using dual PID loops for improved performance in fast systems like drones
- Control Strategy Selection: Choosing appropriate control methods based on system dynamics, precision requirements, computational resources, and energy constraints
- IoT-Specific Considerations: Addressing computational resources, sensor noise, communication latency, and energy constraints in control design
For Kids: Meet the Sensor Squad!
PID is like having THREE helpers working together to reach the perfect target – one watches NOW, one remembers the PAST, and one predicts the FUTURE!
62.8.1 The Sensor Squad Adventure: The Bicycle Race
The Sensor Squad entered a bicycle race! The goal was to ride at EXACTLY 15 km/h – not too fast, not too slow. A speed camera at the finish line would check.
Max the Microcontroller was pedaling. “I need three helpers to keep my speed perfect!”
Helper P (Sammy the Sensor – the “RIGHT NOW” helper): Sammy watched the speedometer every second. “You’re going 10 km/h – that’s 5 km/h too SLOW! Pedal HARDER!” When Max sped up to 14 km/h, Sammy said “Only 1 km/h too slow now – just a LITTLE more pedaling.”
But there was a problem! When Max got to 14.5 km/h, Sammy said “only 0.5 too slow… just a tiny bit more.” Max could never quite reach exactly 15. He was stuck at 14.5!
Helper I (Bella the Battery – the “MEMORY” helper): Bella kept a notebook. “You’ve been 0.5 km/h too slow for 30 whole seconds now! My notebook says it’s time to push a bit EXTRA!” Bella’s memory of all those seconds being too slow added up, giving Max the extra push to reach exactly 15 km/h!
Helper D (Lila the LED – the “PREDICTION” helper): But then Max started going too fast – 15.5 km/h and climbing! Lila watched how QUICKLY the speed was changing. “SLOW DOWN! You’re speeding up fast – if you don’t brake NOW, you’ll zoom past 15 and be going way too fast!” Lila’s prediction helped Max ease off BEFORE overshooting.
Together, the three helpers kept Max at EXACTLY 15 km/h. They won first place for the most accurate speed!
62.8.2 Key Words for Kids
| Helper | Name | What They Do | Real Example |
|---|---|---|---|
| P | Present | Looks at how far you are from the goal RIGHT NOW | “You’re 5 km/h too slow – pedal harder!” |
| I | past (Integral) | Remembers how long you’ve been wrong | “You’ve been too slow for 30 seconds – push extra!” |
| D | future (Derivative) | Predicts what will happen next | “You’re speeding up fast – start braking NOW!” |
62.8.3 Try This at Home!
The Water Pouring Challenge:
- Get a measuring cup and try to pour EXACTLY 200 mL of water from a pitcher
- First try: Pour all at once without looking (just P – react to how far you are)
- Second try: Pour slowly, watching the markings, adjusting as you go (P + I + D!)
- Which method gets closer to exactly 200 mL?
You just used PID control with your own hands and eyes!
62.9 What’s Next
| If you want to… | Read this |
|---|---|
| Study integral and derivative terms in depth | Integral and Derivative Control |
| Explore PID implementation details | PID Implementation and Labs |
| Learn about PID tuning methods | PID Tuning and Applications |
| Study control types comparison | Control Types |
| Practice with the PID simulation lab | PID Simulation Lab |