65  PID Control Simulation Lab

Lab execution time can be estimated before starting runs:

\[ T_{\text{total}} = N_{\text{runs}} \times (t_{\text{setup}} + t_{\text{run}} + t_{\text{review}}) \]

Worked example: With 5 runs and per-run times of 4 min setup, 6 min execution, and 3 min review, total lab time is \(5\times(4+6+3)=65\) minutes. This prevents under-scoping and helps schedule complete experimental cycles.

In 60 Seconds

PID simulation lets you tune controllers before deploying to hardware – saving weeks of trial-and-error. Key metrics to optimize: overshoot (<10% for most IoT systems), settling time (<5 seconds for temperature control), and steady-state error (<0.5% of setpoint). Start with P-only control, add I to eliminate offset, then add D to reduce oscillation. Ziegler-Nichols tuning provides a systematic starting point: find the ultimate gain Ku and oscillation period Tu, then set Kp=0.6Ku, Ki=2Kp/Tu, Kd=Kp*Tu/8.

65.1 Learning Objectives

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

  • Construct Python PID simulations that model realistic temperature control systems
  • Differentiate how proportional, integral, and derivative gains affect transient and steady-state response
  • Measure overshoot percentage, settling time, and steady-state error from simulation output
  • Design temperature, motor, and position control loops for ESP32-based IoT devices
  • Diagnose controller weaknesses when subjected to external disturbance conditions
  • Verify simulation-derived PID parameters before deploying to physical hardware

65.2 Prerequisites

Required Chapters:

Technical Background:

  • Control loop concepts
  • PID controllers
  • System response characteristics

Control System Elements:

Element Function Example
Sensor Measurement Temperature probe
Controller Decision PID algorithm
Actuator Action Valve, motor
Process System HVAC, tank

Lab Requirements:

  • Arduino/ESP32 board
  • Temperature sensor
  • LED or motor for actuation

Estimated Time: 1.5 hours

Cross-Hub Connections

This labs chapter connects to multiple learning resources:

Interactive Tools:

  • Simulations Hub - PID controller simulators and interactive control system tools
  • Try the online PID tuner before hardware implementation

Concept Reinforcement:

Video Tutorials:

  • Videos Hub - Watch PID tuning demonstrations and real-world examples
  • Visual explanations of P, I, and D effects on system response

Knowledge Map:

  • Knowledge Map - See how control systems connect to networking, sensing, and data management

What is this chapter? Practical labs and review for IoT processes and system integration.

When to use:

  • After studying IoT architecture processes
  • When implementing end-to-end systems
  • For hands-on experience

Process Types:

Process Description
Data Collection Sensor to gateway flow
Data Processing Edge and cloud analytics
Control Actuator commands
Management Device provisioning

Lab Focus:

  • Process flow implementation
  • Integration patterns
  • Debugging techniques
  • Performance optimization

Recommended Path:

  1. Review architecture processes fundamentals
  2. Work through labs sequentially
  3. Complete review questions

65.3 Hands-On Lab: PID Control Simulation

In this lab, you’ll experiment with a simulated PID controller to understand how each parameter affects system behavior.

Flowchart diagram of complete IoT process flow showing four stages: Data Acquisition layer (temperature, humidity, pressure sensors generating analog signals), Processing Layer (ADC conversion, signal filtering, PID controller), Control Action Layer (PWM generation driving heater and fan actuators), and Feedback Loop (measuring output, comparing to setpoint, feeding error back to PID controller).

Complete IoT Process Flow from sensors to actuators
Figure 65.1: Complete IoT Process Flow showing four layers: Data Acquisition (temperature, humidity, pressure sensors generating analog signals), Processing Layer (ADC conversion, signal filtering, PID controller calculating control signal), Control Action Layer (PWM generation driving heater and fan), and Feedback Loop (measuring output and comparing to setpoint, feeding error back to PID controller in closed loop)

Comparison diagram showing how each PID term affects system response: P-term provides immediate proportional response to current error, I-term accumulates error over time to eliminate steady-state offset, and D-term responds to rate of error change to dampen overshoot, with example response curves for each combination.

This comparison shows how each PID term affects system behavior. P provides immediate response, I eliminates steady-state error over time, and D predicts and dampens changes. Proper tuning balances these three effects for optimal control.

Temporal sequence diagram showing PID control behavior across multiple control cycles: initial large error drives strong P-term response, D-term applies predictive braking as temperature approaches setpoint, and I-term accumulation at steady state maintains output to compensate for heat loss, illustrating how P, I, and D terms contribute at different phases.
Figure 65.2: Alternative view: Temporal sequence showing PID behavior across control cycles. Initial large error drives strong P-term response. As temperature approaches setpoint, D-term applies “braking” to prevent overshoot. At steady state, I-term accumulation maintains output to compensate for heat loss. This dynamic view illustrates how P, I, and D contribute at different phases.

Complete IoT Process Flow: From Data Acquisition to Control Action

Stage Component Function Output
Data Acquisition Temperature Sensor Measure ambient temperature Analog signal
Humidity Sensor Measure moisture level Analog signal
Pressure Sensor Measure atmospheric pressure Analog signal
Processing Layer ADC Conversion Convert analog to digital Digital values
Signal Filtering Remove noise, smooth data Clean measurements
PID Controller Calculate control output Control signal
Control Action PWM Generation Create pulse-width signal Duty cycle
Heater Heat the environment Temperature change
Fan Cool/ventilate Airflow
Feedback Loop Measure Output Read current state Measured value
Compare to Setpoint Calculate error Error signal → PID

Process Flow: Sensors → ADC → Filter → PID Controller → PWM → Actuators → Measure → Compare → (back to PID)

Common Misconception: “Higher Gains Always Mean Better Performance”

The Myth: Many engineers believe that increasing PID gains (especially Kp) will always improve system response and accuracy.

The Reality: A 2018 industrial IoT deployment at a chemical processing plant learned this lesson the hard way. Engineers increased Kp from 2.0 to 8.0 hoping to reduce temperature settling time from 60s to 20s.

What Actually Happened:

  • Before (Kp=2.0): Settling time 60s, overshoot 2%, oscillation period ~10s (damped in 3 cycles)
  • After (Kp=8.0): System became unstable with continuous oscillation ±5°C
  • Production Impact: 12 batches ($180,000 value) rejected due to temperature excursions
  • Root Cause: Aggressive Kp exceeded stability margin, causing sustained oscillations

The Fix: Ziegler-Nichols tuning identified critical gain Kp_crit = 4.5 (oscillation threshold). Final tuning used Kp = 0.6 × 4.5 = 2.7, Ki = 0.3, Kd = 0.8.

Results: Settling time 35s (vs. 60s original, 42% improvement), zero overshoot, stable operation.

Lesson: There’s an optimal gain range. Below it, response is sluggish. Above it, system becomes unstable. The sweet spot requires systematic tuning, not guessing higher numbers. In control systems, stability always trumps speed.

Interactive Ziegler-Nichols Tuning Calculator:

65.3.1 Lab Objective

Tune P, I, and D gains to achieve optimal control of a simulated temperature system, observing the effects of each parameter.

65.3.2 Simulated System

Consider a smart thermostat controlling room temperature: - Process: Room heating/cooling - Set Point: 22°C - Initial Temperature: 18°C - Disturbance: External temperature changes

65.3.3 Python PID Simulator

State machine diagram of PID control loop showing states: Initialize (set Kp, Ki, Kd, setpoint), Measure (read sensor), Calculate Error (setpoint minus measured), Compute P (Kp times error), Compute I (Ki times integral of error), Compute D (Kd times error rate of change), Sum Output (P+I+D), Limit Output (clamp to min/max), Apply Control (update actuator), with loop back to Measure and anti-windup protection on setpoint change.

PID Control Loop State Machine diagram
Figure 65.3: PID Control Loop State Machine showing control flow from initialization through continuous measurement, error calculation, P/I/D term computation, output limiting, actuator control, and feedback loop with anti-windup protection

PID Control Loop State Machine and Operational Flow

State Action Formula/Notes Next State
Initialize System Startup Set Kp, Ki, Kd, Setpoint Measure
Measure Read Sensor Temperature, Position, Speed Calculate Error
Calculate Error Compute error error = setpoint - measured Compute P
Compute P Proportional term P = Kp × error (fast response) Compute I
Compute I Integral term I = Ki × ∫error·dt (eliminates steady-state) Compute D
Compute D Derivative term D = Kd × (Δerror/Δt) (reduces overshoot) Sum Output
Sum Output Combine terms output = P + I + D Limit Output
Limit Output Clamp value Constrain to [min, max] Apply Control
Apply Control Update Actuator PWM, Valve, Motor Measure (loop)
Check Setpoint New setpoint? If changed → Reset Integral Calculate Error
Shutdown Exit command Stop control loop End

Anti-Windup: Integral term is reset when setpoint changes significantly to prevent overshoot from accumulated error.

65.3.4 Lab Tasks

Task 1: P-Only Control

Set Kp=2.0, Ki=0.0, Kd=0.0 and run the simulation.

Observe:

  • How quickly does temperature rise initially?
  • Does the system reach exactly 22°C?
  • What happens at t=50s when the disturbance occurs?
  • Is there steady-state error?

Expected Results:

  • Fast initial response
  • Settles with offset (steady-state error ~0.5-1°C)
  • Disturbance causes permanent offset increase
  • Some oscillation possible
Task 2: PI Control

Set Kp=2.0, Ki=0.5, Kd=0.0 and run the simulation.

Observe:

  • Does the system now reach exactly 22°C?
  • How does the response compare to P-only?
  • What happens to the disturbance-induced offset?
  • Is there any overshoot?

Expected Results:

  • Eliminates steady-state error
  • Reaches exactly 22°C eventually
  • Recovers from disturbance automatically
  • Possible overshoot and longer settling time
Task 3: Full PID Control

Set Kp=2.0, Ki=0.5, Kd=1.0 and run the simulation.

Observe:

  • How does overshoot compare to PI?
  • Is settling time improved?
  • How does the system respond to the disturbance?
  • Look at the D term plot - when is it most active?

Expected Results:

  • Minimal overshoot
  • Faster settling time
  • Quick disturbance rejection
  • D term most active during rapid changes
Task 4: Parameter Tuning Exploration

Experiment with different gain values:

Test these scenarios:

  1. Aggressive P: Kp=5.0, Ki=0.5, Kd=1.0
    • What happens?
  2. Too Much I: Kp=2.0, Ki=2.0, Kd=0.0
    • Does it overshoot significantly?
  3. Excessive D: Kp=2.0, Ki=0.5, Kd=5.0
    • Does response become sluggish?
  4. Balanced Tuning: Find optimal values for:
    • Minimal overshoot (<0.5°C)
    • Fast settling (<30s)
    • Zero steady-state error

Flowchart showing progressive PID tuning lab workflow: start with system setup, then Task 1 P-only control (Kp=2.0), then Task 2 PI control (adding Ki=0.5), then Task 3 full PID (adding Kd=1.0), then Task 4 parameter exploration with variations, leading to final optimization and hardware implementation on ESP32.

PID Tuning Lab Workflow flowchart
Figure 65.4: PID Tuning Lab Workflow showing progressive experimentation from P-only control through PI and full PID, with exploration of parameter variations and final optimization before hardware implementation

PID Tuning Lab Workflow and Experimental Process

Task Parameters Expected Observations Next Step
Setup System parameters Configure simulation Task 1
Task 1: P-Only Kp=2.0, Ki=0, Kd=0 Error ~1°C, fast initial response, possible oscillation Task 2
Task 2: PI Control Kp=2.0, Ki=0.5, Kd=0 Zero steady-state error, some overshoot, longer settling Task 3
Task 3: Full PID Kp=2.0, Ki=0.5, Kd=1.0 Minimal overshoot, fast settling, zero SS error Task 4
Task 4: Exploration Various test cases Compare different configurations Optimize

Exploration Tests:

Test Parameters What to Observe
Aggressive P Kp=5.0, Ki=0.5, Kd=1.0 Increased oscillation, faster response
Excessive I Kp=2.0, Ki=2.0, Kd=0 Significant overshoot, slow settling
High D Kp=2.0, Ki=0.5, Kd=5.0 Sluggish response, noise sensitivity

Performance Metrics to Measure:

  1. Rise Time - Time to reach 90% of setpoint
  2. Settling Time - Time to stay within ±2% of setpoint
  3. Overshoot % - Maximum deviation above setpoint
  4. Steady-State Error - Final offset from setpoint

Final Step: Hardware Implementation on ESP32 → Validate on Real System → Lab Complete

65.3.5 Arduino PID Implementation

For real hardware implementation with ESP32:

// ESP32 PID Temperature Controller
#include <Arduino.h>

class PIDController {
    float kp, ki, kd, setpoint;
    float integral = 0, previous_error = 0;
    unsigned long last_time = 0;
public:
    PIDController(float Kp, float Ki, float Kd, float sp)
        : kp(Kp), ki(Ki), kd(Kd), setpoint(sp) {}

    float update(float measured) {
        unsigned long now = millis();
        float dt = last_time ? (now - last_time) / 1000.0 : 0;
        float error = setpoint - measured;

        float P = kp * error;
        integral = constrain(integral + error * dt, -100, 100);
        float I = ki * integral;
        float D = dt > 0 ? kd * (error - previous_error) / dt : 0;

        previous_error = error;
        last_time = now;
        return P + I + D;
    }
};

The main program reads a TMP36 sensor and drives a heater via PWM:

#define TEMP_SENSOR_PIN 34
#define HEATER_PWM_PIN  25

PIDController pid(2.0, 0.5, 1.0, 22.0);

float readTemperature() {
    float voltage = analogRead(TEMP_SENSOR_PIN) * (3.3 / 4095.0);
    return (voltage - 0.5) * 100.0;  // TMP36 conversion
}

void setup() {
    Serial.begin(115200);
    ledcSetup(0, 5000, 8);
    ledcAttachPin(HEATER_PWM_PIN, 0);
}

void loop() {
    float temp = readTemperature();
    int pwm = constrain((int)pid.update(temp), 0, 255);
    ledcWrite(0, pwm);
    Serial.printf("%.1fs: temp=%.1f, pwm=%d\n", millis()/1000.0, temp, pwm);
    delay(100);
}

Scenario: After tuning PID gains in Python simulation (Kp=2.0, Ki=0.5, Kd=1.0 for temperature control), convert to fixed-point integer math for Arduino Uno (no floating-point hardware).

Simulation Results (Floating-Point):

def pid_update(error, prev_error, integral, dt=1.0):
    Kp, Ki, Kd = 2.0, 0.5, 1.0
    P = Kp * error
    integral += error * dt
    I = Ki * integral
    D = Kd * (error - prev_error) / dt
    return P + I + D

Arduino Fixed-Point Conversion:

// Scale factor: 100 (2 decimal places precision)
#define KP 200    // 2.0 * 100
#define KI 50     // 0.5 * 100
#define KD 100    // 1.0 * 100
#define SCALE 100

int16_t pid_update(int16_t error, int16_t prev_error, int32_t *integral) {
    // Error in 0.01°C units (e.g., 250 = 2.50°C)
    int16_t P = (error * KP) / SCALE;               // Proportional
    *integral += error;                              // Accumulate integral
    int16_t I = (int16_t)((*integral * KI) / SCALE); // Integral with overflow check
    int16_t D = ((error - prev_error) * KD) / SCALE; // Derivative

    // Anti-windup: clamp integral to ±10000 (±100°C·sec)
    if (*integral > 10000) *integral = 10000;
    if (*integral < -10000) *integral = -10000;

    return P + I + D;  // Output in 0.01% units
}

Test Case Verification:

Time Error (°C) P I (∫error) D Output Python Output Match?
T=0 5.00 1000 0 0 1000 10.00
T=1 3.50 700 425 -150 975 9.75
T=2 2.00 400 525 -150 775 7.75

Key Insight: Fixed-point math with SCALE=100 preserves 2 decimal places precision while running 10× faster on Arduino Uno (no floating-point hardware). Always test edge cases (overflow, negative values) in simulation before deploying to MCU.

System Time Constant Recommended Sample Period Reasoning Example
<1 second (fast) 1-10 ms 10-100× faster than dynamics Drone attitude control (IMU: 1 kHz sampling)
1-10 seconds (moderate) 100-500 ms 5-20× faster than dynamics Motor speed control (encoder: 200 Hz)
10-60 seconds (slow) 1-5 seconds Sample 5-10× per time constant HVAC temperature (DHT22: 1 Hz)
>1 minute (very slow) 10-60 seconds Avoid wasting power on redundant samples Soil moisture (once per minute)

Rule: Sample 5-10× faster than system time constant. Faster sampling improves D-term responsiveness but increases CPU/power usage.

Common Mistake: Forgetting Anti-Windup in Real Hardware

The Mistake: Simulation includes anti-windup (integral = constrain(integral, -100, 100)) but engineer forgets to implement it in ESP32 firmware. After 48 hours of runtime during cold start (error > 0 continuously), integral accumulates to 45,000, causing massive overshoot.

Real Example: Smart greenhouse heater left running overnight with target 22°C, ambient 5°C. By morning, integral = 61,200 (17 hours × 3600 seconds × 1°C error). When sun rose and greenhouse warmed naturally, heater stayed on at 100% for additional 25 minutes (burning off integral), reaching 38°C and killing seedlings.

The Fix: Always implement clamping in production code:

integral += error * dt;
integral = constrain(integral, -10000, 10000);  // Clamp to ±27.7 hours of 1°C error

Test: Let controller run for 24 hours with constant 5°C error, verify integral does not exceed clamp limits.

Key Concepts

  • MATLAB/Simulink: MathWorks software environment providing PID simulation blocks, transfer function analysis, step response plotting, and automated PID tuning tools widely used in control systems education and engineering
  • Python Control Library: An open-source Python package (control) providing transfer function creation, frequency response analysis, step response simulation, and root locus plotting for control system design
  • Step Response: The time-domain output of a system when the input changes instantaneously from one value to another — used to extract process parameters (gain, time constant, dead time) for PID tuning
  • Simulation Time Step: The integration step size in numerical PID simulation — must be small compared to the smallest time constant in the system; typical values are 0.001 to 0.1 times the process time constant
  • Transfer Function Simulation: Representing the process and controller as mathematical expressions G(s) in the Laplace domain and numerically computing the time-domain response using integration methods (Euler, Runge-Kutta)
  • Performance Index: A scalar metric summarizing closed-loop control quality (ISE, IAE, ITAE) computed by integrating the squared or absolute error over time — used to objectively compare alternative PID tuning approaches

Common Pitfalls

Running a PID simulation with time step larger than the process time constant. Integration accuracy deteriorates and the simulation may show false stability or instability not present in the real system. Use simulation time step ≤ τ/100 for accurate results.

Reporting simulation results as representative of real system behavior without hardware validation. Simulation models have simplified assumptions — real hardware has actuator nonlinearity, sensor noise, communication delays, and parameter uncertainty absent from simulation.

Optimizing PID gains until the simulation shows near-perfect setpoint tracking, then discovering the gains are unstable on hardware due to model uncertainty. Detune gains by 20–30% from simulation optimal to ensure robustness to real-world parameter variations.

Simulating at 1000 Hz (common in MATLAB) but implementing on hardware at 50 Hz due to microcontroller constraints. The same PID gains behave differently at different sample rates. Simulate at the actual hardware sample rate to ensure simulation-to-hardware transfer.

65.4 Summary

This lab provided hands-on experience with PID control simulation and implementation:

Key Accomplishments:

  1. P-Only Control: Demonstrated fast response but persistent steady-state error
  2. PI Control: Showed how integral action eliminates steady-state error
  3. PID Control: Achieved optimal response with minimal overshoot
  4. Parameter Exploration: Learned the effects of aggressive tuning

Performance Metrics Learned:

  • Rise time, settling time, overshoot percentage, steady-state error

Hardware Implementation:

  • Complete ESP32 PID controller code ready for deployment
  • Anti-windup protection for real-world robustness

Next Steps:

Prerequisites:

Continue Learning:

Key Takeaways
  • Simulate before deploying: PID simulation saves weeks of trial-and-error on real hardware and prevents dangerous actuator oscillation
  • Progressive tuning: Always start P-only, then add I, then D – never tune all three at once
  • Key metrics: Rise time (speed to reach target), settling time (time to stabilize), overshoot (how far past target), steady-state error (permanent offset)
  • Anti-windup is essential: Without integral clamping, the I-term can accumulate to extreme values during large errors, causing massive overshoot when the system finally responds
  • Ziegler-Nichols method: Find the gain where the system oscillates (Ku), measure the oscillation period (Tu), then calculate Kp=0.6Ku, Ki=2Kp/Tu, Kd=Kp*Tu/8

Practicing in a SIMULATION first is like using training wheels before riding a real bike!

65.4.1 The Sensor Squad Adventure: The Virtual Practice Room

Before the Sensor Squad could control REAL machines, they needed to practice in a safe place. Max the Microcontroller had built a “Virtual Practice Room” – a computer simulation of a real oven!

“Why can’t we just use the REAL oven?” asked Sammy the Sensor.

“Because,” Max explained, “if I mess up the controls in real life, the oven could get WAY too hot and break! In the simulation, nothing bad happens if we make mistakes. We can try crazy things and learn from them!”

They started experimenting:

Experiment 1: Max set his P-control to MAXIMUM. In the simulation, the virtual oven heated up super fast… then cooled down… then heated up… bouncing back and forth like a yo-yo! “Whoa! Too aggressive!” laughed Max.

Experiment 2: Max added a HUGE integral term. The virtual oven slowly crept up to the target temperature… then ZOOMED past it to 50 degrees too hot! “The integral remembered TOO much and overreacted!” said Bella.

Experiment 3: Max found the perfect balance. The virtual oven smoothly rose to exactly the right temperature and stayed there. “NOW we’re ready for the real oven!” cheered Lila.

When they finally connected to the REAL oven, the settings from their simulation worked perfectly on the first try!

“See?” said Max. “Simulation is like having UNLIMITED practice attempts with ZERO risk. Real engineers ALWAYS simulate before building!”

65.4.2 Try This at Home!

The “Simulation” Game:

  1. Put a cup of water in front of you and a thermometer in it
  2. WITHOUT touching the water, PREDICT: if you add 3 ice cubes, how cold will it get?
  3. Write down your prediction (this is your “simulation”!)
  4. Now add the ice cubes and measure the REAL temperature
  5. How close was your prediction? Engineers do this with computers to practice millions of times!

65.5 What’s Next?

Now that you’ve gained hands-on experience with PID simulation, continue to the understanding checks to test your knowledge with real-world scenarios.

Continue to Understanding Checks →

Previous Up Next
Processes Labs and Review Reference Architectures Understanding Checks