65 PID Control Simulation Lab
Putting Numbers to It
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.
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:
- Processes and Systems - Process control basics
- Sensor Fundamentals - Sensors
- Actuators - Actuators
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:
- Quizzes Hub - Test control system understanding with targeted quizzes
- Knowledge Gaps Hub - Address common PID misconceptions
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
For Beginners: How to Use This Labs Chapter
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:
- Review architecture processes fundamentals
- Work through labs sequentially
- 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.
Alternative View: PID Tuning Effects Comparison
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.
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
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
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:
- Rise Time - Time to reach 90% of setpoint
- Settling Time - Time to stay within ±2% of setpoint
- Overshoot % - Maximum deviation above setpoint
- 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);
}
Worked Example: Converting Python Simulation Results to Arduino Implementation
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 + DArduino 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.
Decision Framework: Choosing PID Sample Period
| 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 errorTest: 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
1. Choosing Simulation Time Step Too Large
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.
2. Not Validating Simulation Against Real Hardware
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.
3. Tuning for Perfect Simulation Performance, Not Robustness
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.
4. Using the Same Sample Rate in Simulation and Implementation
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:
- P-Only Control: Demonstrated fast response but persistent steady-state error
- PI Control: Showed how integral action eliminates steady-state error
- PID Control: Achieved optimal response with minimal overshoot
- 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:
- Understanding Checks - Test your understanding with real-world scenarios
- Decision Guidance - Apply decision frameworks for control system design
Related Chapters
Prerequisites:
- Processes and Systems - Control theory fundamentals
- Sensor Fundamentals - Measurement principles
- Actuators - Control action mechanisms
Continue Learning:
- Understanding Checks - Scenario-based learning
- Decision Guidance - Practical decision frameworks
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
For Kids: Meet the Sensor Squad!
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:
- Put a cup of water in front of you and a thermometer in it
- WITHOUT touching the water, PREDICT: if you add 3 ice cubes, how cold will it get?
- Write down your prediction (this is your “simulation”!)
- Now add the ice cubes and measure the REAL temperature
- 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 |