Implement a PID controller in Arduino/ESP32 C++ code
Use Python to simulate and tune PID controllers
Apply anti-windup techniques to prevent integral saturation
Tune PID parameters using systematic approaches
Analyze PID performance metrics (settling time, overshoot, steady-state error)
234.2 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.
234.2.1 Lab Objective
Tune P, I, and D gains to achieve optimal control of a simulated temperature system, observing the effects of each parameter.
234.2.2 Simulated System
Consider a smart thermostat controlling room temperature: - Process: Room heating/cooling - Set Point: 22C - Initial Temperature: 18C - Disturbance: External temperature changes
234.2.3 Lab Tasks
NoteTask 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 22C? - 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-1C) - Disturbance causes permanent offset increase - Some oscillation possible
NoteTask 2: PI Control
Set Kp=2.0, Ki=0.5, Kd=0.0 and run the simulation.
Observe: - Does the system now reach exactly 22C? - 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 22C eventually - Recovers from disturbance automatically - Possible overshoot and longer settling time
NoteTask 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
NoteTask 4: Parameter Tuning Exploration
Experiment with different gain values:
Test these scenarios:
Aggressive P: Kp=5.0, Ki=0.5, Kd=1.0
What happens?
Too Much I: Kp=2.0, Ki=2.0, Kd=0.0
Does it overshoot significantly?
Excessive D: Kp=2.0, Ki=0.5, Kd=5.0
Does response become sluggish?
Balanced Tuning: Find optimal values for:
Minimal overshoot (<0.5C)
Fast settling (<30s)
Zero steady-state error
234.3 Arduino PID Implementation
For real hardware implementation with ESP32:
// ESP32 PID Temperature Controller#include <Arduino.h>class PIDController {private:float kp, ki, kd;float setpoint;float integral;float previous_error;unsignedlong last_time;public: PIDController(float Kp,float Ki,float Kd,float sp): kp(Kp), ki(Ki), kd(Kd), setpoint(sp), integral(0), previous_error(0), last_time(0){}float update(float measured_value){unsignedlong current_time = millis();float dt =(current_time - last_time)/1000.0;// Convert to secondsif(last_time ==0) dt =0;// First call// Calculate errorfloat error = setpoint - measured_value;// Proportionalfloat P = kp * error;// Integral (with anti-windup) integral += error * dt; integral = constrain(integral,-100,100);// Limit integralfloat I = ki * integral;// Derivativefloat derivative =(error - previous_error)/ dt;float D = kd * derivative;// Update state previous_error = error; last_time = current_time;// Calculate outputreturn P + I + D;}void setSetpoint(float sp){ setpoint = sp;}void reset(){ integral =0; previous_error =0; last_time =0;}};// Pin definitions#define TEMP_SENSOR_PIN 34// ADC pin for temperature sensor#define HEATER_PWM_PIN 25// PWM output for heater control// PID parametersconstfloat KP =2.0;constfloat KI =0.5;constfloat KD =1.0;constfloat SETPOINT =22.0;// Target temperature in CPIDController pid(KP, KI, KD, SETPOINT);// PWM configurationconstint pwmFreq =5000;constint pwmChannel =0;constint pwmResolution =8;// 8-bit: 0-255void setup(){ Serial.begin(115200);// Configure PWM for heater control ledcSetup(pwmChannel, pwmFreq, pwmResolution); ledcAttachPin(HEATER_PWM_PIN, pwmChannel); Serial.println("ESP32 PID Temperature Controller"); Serial.println("Time(s),Setpoint,Temperature,Output,P,I,D");}float readTemperature(){// Read analog value from temperature sensorint adcValue = analogRead(TEMP_SENSOR_PIN);// Convert ADC to temperature (example for TMP36)// TMP36: 10mV/C, 500mV offset at 0Cfloat voltage = adcValue *(3.3/4095.0);// ESP32 12-bit ADCfloat temperature =(voltage -0.5)*100.0;return temperature;}void loop(){// Read current temperaturefloat current_temp = readTemperature();// Calculate PID outputfloat pid_output = pid.update(current_temp);// Convert to PWM duty cycle (0-255)int pwm_value = constrain((int)pid_output,0,255);// Apply to heater ledcWrite(pwmChannel, pwm_value);// Log data Serial.print(millis()/1000.0); Serial.print(","); Serial.print(SETPOINT); Serial.print(","); Serial.print(current_temp); Serial.print(","); Serial.println(pwm_value); delay(100);// Update every 100ms}
234.4 Interactive Quiz
Test your understanding of processes, systems, and PID control:
CautionQuestion 1: Process vs System
What is the key difference between a process and a system in IoT devices?
A) A process is hardware, a system is software B) A process is the algorithm/program, a system is all components working together C) A process handles inputs, a system handles outputs D) There is no difference
Answer
B) A process is the algorithm/program, a system is all components working together
Explanation: - Process: The series of actions or steps (typically the program running on the microcontroller) that transform inputs into outputs - System: The complete interconnected set of components (microcontroller, sensors, actuators, power supply, etc.) that work together to perform a function - Example: In a smart thermostat, the temperature control algorithm is the process, while the entire device with sensors, heater control, and user interface is the system
CautionQuestion 2: Open-Loop Limitation
A smart irrigation system waters plants for exactly 10 minutes every morning at 6 AM, regardless of soil moisture, weather, or plant needs. What is the primary limitation of this open-loop design?
A) It’s too expensive to implement B) It cannot self-correct and may over-water or under-water C) It uses too much power D) It’s too complex for most users
Answer
B) It cannot self-correct and may over-water or under-water
Explanation: This is a classic open-loop system problem: - System operates based on predetermined schedule (time-based control) - No feedback about actual soil moisture or plant needs - Cannot adapt to: - Recent rainfall (may over-water) - Hot, dry weather (may under-water) - Different plant species with varying needs - Seasonal changes - Solution: Add soil moisture sensor and close the loop, watering only when soil moisture drops below threshold
Open-loop is acceptable when: - Environment is highly predictable - Precision is not critical - Cost is primary constraint - But for irrigation, closed-loop is strongly recommended
CautionQuestion 3: PID Term Identification
Your smart oven is heating up to 180C. Currently at 160C, the temperature is rising rapidly at 5C per second. Which PID term will act to reduce the heating power to prevent overshooting 180C?
A) Proportional (P) term B) Integral (I) term C) Derivative (D) term D) None - overshoot is unavoidable
Answer
C) Derivative (D) term
Explanation: The derivative term reacts to the rate of change of error:
Current Situation: - Set Point (SP): 180C - Current Temperature (PV): 160C - Error: +20C (need more heat) - Rate of change: +5C/s (temperature rising rapidly)
PID Term Responses:
P term: Reacts to current error magnitude
Error = +20C so P wants to add heat
P doesn’t know temperature is rising rapidly
I term: Reacts to accumulated past error
Integral has been accumulating positive error
I wants to continue adding heat
I doesn’t anticipate future
D term: Reacts to error rate of change
Error was +40C, now +20C so error decreasing at -5C per second
Negative derivative (error decreasing) produces negative D output
D term reduces heating power to prevent overshoot
Acts as “predictive brake”
Without D term: Oven would overshoot to ~185C, then oscillate With D term: Oven smoothly approaches 180C with minimal overshoot
Key Insight: D term provides “damping” by anticipating where the system is heading
CautionQuestion 4: Steady-State Error
You implement a P-only temperature controller for an aquarium heater. The system settles at 24.3C when the set point is 25.0C. Which action will eliminate this 0.7C steady-state error?
A) Increase Kp gain B) Add integral (I) control C) Add derivative (D) control D) Decrease Kp gain
Answer
B) Add integral (I) control
Explanation:
Why P-only has steady-state error:
Proportional control output = Kp times Error
When system settles: - Error = 25.0 - 24.3 = 0.7C - P output = Kp times 0.7C - This small output only maintains current temperature - It’s not enough to eliminate the remaining 0.7C error - System is “stuck” with persistent offset
Why other options don’t work:
A) Increase Kp: - Reduces steady-state error but doesn’t eliminate it - May cause overshoot and oscillation - Still leaves some offset
C) Add D control: - D only responds to changing error (de/dt) - At steady state, error is constant (de/dt = 0) - D contributes nothing at steady state
D) Decrease Kp: - Makes steady-state error worse! - Weaker response to error
Why I control works:
Integral accumulates error over time: - Error = 0.7C persists - Integral keeps growing: integral of 0.7 dt = 0.7t - Integral output increases continuously - Heater power increases until temperature reaches 25.0C - Only when error = 0 does integral stop growing
Result with PI control: - System reaches exactly 25.0C - Steady-state error eliminated - Integral maintains whatever output is needed to hold temperature
CautionQuestion 5: Distributed Feedback
An IoT water quality monitoring system measures dissolved oxygen (DO) levels in a fish farm. When DO drops below 5 mg/L, a cloud-based alert triggers an aeration pump via a remote actuator node. Is this a closed-loop or open-loop system?
A) Open-loop, because individual nodes don’t have feedback B) Closed-loop, because there’s feedback at the system level C) Neither, it’s purely a monitoring system D) Both, depending on perspective
Answer
D) Both, depending on perspective (though B is also a valid answer)
Explanation:
This question highlights an important concept in distributed IoT systems: feedback can exist at different architectural levels.
Local Device Perspective (Open-Loop): - Sensor node: Measures DO, transmits data - Open-loop (no local actuation) - Actuator node: Receives command, runs pump - Open-loop (no local sensing) - Neither device individually implements closed-loop control
System Perspective (Closed-Loop):
%%{init: {'theme': 'base', 'themeVariables': { 'primaryColor': '#2C3E50', 'primaryTextColor': '#fff', 'primaryBorderColor': '#16A085', 'lineColor': '#16A085', 'secondaryColor': '#E67E22', 'tertiaryColor': '#ecf0f1', 'fontSize': '14px'}}}%%
graph TB
subgraph Edge ["Edge Devices"]
S["DO Sensor:<br/>Reads 6.2 mg/L<br/>(Open-Loop)"]
A["Aeration Pump<br/>Actuator<br/>(Open-Loop)"]
end
subgraph Cloud ["Cloud Control System"]
P["IoT Platform"]
R["Control Logic:<br/>IF DO < 7 mg/L<br/>THEN Pump = ON"]
end
S -->|Upload Reading| P
P --> R
R -->|Command:<br/>Activate Pump| A
A -->|Increase DO| Water["Fish Farm<br/>Water"]
Water -.->|Feedback:<br/>Measure New DO| S
Note["System-Level<br/>Closed-Loop<br/>via Cloud"] -.-> R
style S fill:#2C3E50,stroke:#16A085,stroke-width:2px,color:#fff
style A fill:#E67E22,stroke:#16A085,stroke-width:2px,color:#fff
style P fill:#16A085,stroke:#2C3E50,stroke-width:2px,color:#fff
style R fill:#E67E22,stroke:#16A085,stroke-width:2px,color:#fff
style Note fill:#16A085,stroke:#2C3E50,stroke-width:3px,color:#fff
Figure 234.1: Fish farm cloud-based dissolved oxygen control loop
Distributed IoT Feedback Architecture: Individual edge devices (sensor, actuator) operate open-loop with no local control logic. Cloud platform closes the feedback loop by coordinating sensing and actuation across network, creating system-level closed-loop control.
This IS closed-loop feedback because: 1. Set point exists (DO > 5 mg/L) 2. Output measured (DO sensor reads actual DO) 3. Error calculated (cloud compares SP vs measured) 4. Control action taken (pump activated if error) 5. Feedback path exists: Pump action affects DO level, which is measured by sensor
Key Difference from Traditional Closed-Loop: - Distributed architecture: Components separated across network - Network latency: Feedback delay due to communication - Cloud processing: Decision-making in cloud instead of local controller - Still closed-loop: Feedback path exists, even if distributed
Practical Implications: - Slower response than local closed-loop (network latency) - Enables centralized monitoring and coordination - Single point of failure if cloud connectivity lost - Could add local closed-loop as backup for critical control
Best Answer: D because the answer depends on your level of analysis (device vs system), though B correctly identifies the system-level feedback that ultimately matters for control performance.
234.5 Python PID Implementation
234.5.1 PID Controller for IoT Systems
Key Features: 1. Complete PID Implementation: Proportional, Integral, and Derivative terms 2. Anti-Windup: Prevents integral term saturation 3. Derivative Filtering: Reduces high-frequency noise 4. Plant Simulation: First-order system with time delay 5. Performance Metrics: Steady-state error, overshoot, rise time
This section provides a comprehensive, production-ready Python framework for IoT control systems, implementing PID controllers, open-loop and closed-loop architectures, system simulation, and auto-tuning capabilities.
This production framework provides comprehensive IoT control system capabilities including:
PID Controller: Full PID implementation with anti-windup, output limiting, and configurable modes (P, PI, PD, PID)
Plant Models: First-order, thermal, and motor dynamics with realistic physics
System Simulation: Closed-loop and open-loop simulation with disturbance injection
Auto-Tuning: Ziegler-Nichols and Cohen-Coon tuning methods
Performance Analysis: 7 metrics including rise time, settling time, overshoot, and integral errors
The framework demonstrates production-ready patterns for IoT control systems with realistic plant models, comprehensive performance analysis, and auto-tuning capabilities.
NoteComprehensive Review Quiz
Question 1: A smart greenhouse uses a timer to turn on irrigation for 10 minutes every 6 hours, regardless of soil moisture. What type of system is this?
Explanation: Open-loop system operates without sensing output state. Characteristics: Fixed schedule (10min every 6hrs), no soil moisture sensor, no adaptation to actual conditions. Problems: Over-watering after rain, under-watering during heat waves, wasted water/energy. Closed-loop alternative: Soil moisture sensor to controller reads moisture and irrigates only when moisture below threshold then stops when moisture adequate. Real-world impact: Open-loop irrigation wastes 40-60% water versus closed-loop smart systems. The lack of feedback is the defining characteristic of open-loop control.
Question 2: An industrial oven uses PID control (Kp=10, Ki=2, Kd=1). Current error=5C, integral sum=20C-s, error rate=2C/s. What is the total controller output?
Explanation: PID output = P + I + D components. Proportional: Kp times error = 10 times 5 = 50 units. Integral: Ki times accumulated error = 2 times 20 = 40 units. Derivative: Kd times error rate = 1 times 2 = 2 units. Total = 50 + 40 + 2 = 92 units of heating power. Interpretation: Large current error (P=50) + persistent past error (I=40) + rapid change detected (D=2) = aggressive correction. As oven approaches setpoint: error decreases (P decreases), accumulated error decreases (I decreases), rate decreases (D decreases) leading to smooth convergence. This demonstrates how PID combines three perspectives: present, past, and future.
Question 3: A distributed IoT system has 100 temperature sensors and 20 heaters. Where should the feedback control logic run?
Explanation: Hierarchical control architecture: Local control loops (edge): Each heater has local PID controller reading nearby sensors giving less than 10ms latency and stable control even if cloud offline. Coordination (fog/cloud): Balances heating across zones, optimizes energy, adjusts setpoints, monitors performance. Why local control critical: Temperature control needs fast feedback (~1s). Cloud round-trip (100-500ms) creates instability. Example: Smart building - 20 zone controllers (edge) maintain temperature locally, building controller (cloud) optimizes overall strategy. Result: Resilient (works offline), efficient (fast local response), intelligent (cloud optimization).
Question 4: A manufacturing IoT system processes 10,000 sensor readings/second through a data pipeline: raw data to filtering to feature extraction to analytics to storage. At what layer should feature extraction occur?
Explanation: Edge feature extraction optimizes bandwidth and latency: Data volume: 10,000 readings/s times 4 bytes = 40 KB/s raw data = 3.5 GB/day. Feature extraction: 10s window to compute mean, std dev, min, max, FFT peaks (10 features) gives 100 features/s times 4 bytes = 0.4 KB/s = 35 MB/day (99% reduction). Why not sensor: Resource-constrained, limited compute. Why not cloud: Bandwidth cost ($0.09/GB AWS = $315/month for raw vs $3/month for features), latency for real-time analytics. Why not storage: Features needed for real-time decisions. Example: Vibration monitoring - 10,000 Hz accelerometer where edge extracts frequency spectrum (5 dominant frequencies) so cloud gets 5 values instead of 10,000 samples and anomaly detection runs in real-time. This is edge computing’s killer app: intelligent preprocessing reduces cloud traffic 100-1000x.
Question 5: A smart grid IoT system collects power consumption data from 50,000 smart meters every 15 minutes. Where should the data aggregation (summing neighborhood consumption) occur?
Explanation: Fog-layer aggregation balances efficiency and functionality: Fog approach: Each neighborhood substation (fog node) aggregates 1000 nearby meters, computes neighborhood total, peak load, power factor, and sends 1 summary message to cloud. Data reduction: 50,000 individual meter readings to 50 neighborhood summaries (1000x reduction). Bandwidth: Raw: 50K meters times 100 bytes times 4 times/hour = 20 MB/hour. Aggregated: 50 summaries times 200 bytes times 4/hour = 40 KB/hour (99.8% reduction). Latency: Local aggregation less than 1s vs cloud aggregation greater than 10s (network round-trips). Privacy: Individual consumption stays local, only aggregates go to cloud. Why not cloud: Overwhelming bandwidth, privacy concerns, latency. Why not meters: Need neighborhood view for load balancing. Real deployment: PG&E smart grid uses fog nodes at substations for local aggregation and analytics, reducing cloud traffic while enabling real-time grid management. This is fog computing textbook use case.
Question 6: An industrial IoT system monitors pump vibration using FFT analysis to detect bearing failures. The vibration sensor outputs 10,000 samples/second. What processing architecture makes sense?
Explanation: Edge analytics for predictive maintenance: Raw data: 10K samples/s times 2 bytes = 20 KB/s = 1.7 GB/day per sensor. 100 sensors = 170 GB/day (prohibitive cloud bandwidth). Edge processing: Collect 1-second window (10K samples) then FFT (frequency spectrum) then extract 5 dominant frequencies + amplitudes then detect anomalies (compare to baseline) then send only “bearing resonance detected at 1.8 kHz, amplitude 0.8g” to cloud. Data reduction: 10K samples to 10 bytes message (99.9% reduction). Real-time: Edge detects anomaly in less than 1s leading to immediate alert. Cloud approach: batch upload then queued processing then alert delayed 10-60s. ML enhancement: Train baseline model in cloud, deploy to edge where edge compares live FFT to model and flags deviations. Why not (C): Reducing sampling loses high-frequency bearing failure signatures (1-3 kHz requires greater than 6 kHz sampling by Nyquist). Industrial reality: Siemens MindSphere, GE Predix use edge FFT and only send anomalies, reducing bandwidth 1000x.
Question 7: A multi-tenant IoT platform serves 500 customers with isolated data and separate processing pipelines. What system architecture ensures proper isolation?
Explanation: Microservices + containers provide strong multi-tenancy isolation: Architecture: Each customer gets: (1) Isolated microservice instances (data ingestion, processing, API), (2) Separate database/schema, (3) Network isolation via virtual LANs, (4) Resource limits (CPU, memory quotas). Security: Customer A’s data cannot leak to Customer B (physical separation). SQL injection in Customer A’s service doesn’t affect others. Scalability: Customer A has 100K devices so allocate 10 service instances. Customer B has 1K devices so allocate 1 instance. Independent scaling. Deployment: Update Customer A’s analytics without touching Customer B. Example: AWS IoT Core uses this - each customer gets isolated resources, separate endpoints, encrypted communication. Why not monolithic: Single codebase, shared database leading to security risks, resource contention, one customer’s load affects others. Why not shared DB: Risk of data leakage, complex access control, performance interference. Container orchestration (Kubernetes) manages 500 customers’ isolated environments efficiently. This architecture balances isolation, scalability, and cost.
234.7 Summary
This chapter provided hands-on implementation guidance for PID control systems.
Key Takeaways:
ESP32 Implementation: Complete PID controller class with anti-windup, suitable for real hardware deployment
Lab Exercises: Systematic exploration of P, PI, and PID configurations to build intuition for tuning
Performance Metrics: Steady-state error, overshoot, settling time are key indicators of control quality
Production Framework: Auto-tuning (Ziegler-Nichols, Cohen-Coon), plant models, and comprehensive simulation capabilities
Distributed Control: System-level feedback can span cloud and edge, but local control loops minimize latency
Edge Processing: Feature extraction and analytics at the edge reduces bandwidth 100-1000x for high-frequency sensor data
234.8 Further Reading
Control Theory Fundamentals: - Ogata, K. (2010). Modern Control Engineering. Prentice Hall. - Astrom, K. J., & Murray, R. M. (2021). Feedback Systems: An Introduction for Scientists and Engineers. Princeton University Press.
This chapter established the practical implementation of PID control systems for IoT applications.
System Fundamentals: We explored how PID controllers are implemented in both Arduino/ESP32 C++ and Python, with anti-windup mechanisms and proper gain tuning.
Feedback and Control: The labs demonstrated how P-only, PI, and PID configurations behave differently, building intuition for when to use each approach.
Distributed Architecture: We examined how feedback loops can span edge and cloud, with local control loops handling time-critical responses and cloud coordination optimizing overall system performance.
These implementation skills prepare you for deploying real PID controllers in IoT applications from temperature control to motor speed regulation.
234.10 What’s Next?
Having mastered PID control theory and implementation, we now examine multi-hop ad-hoc networks. The next chapter builds upon these control foundations to explore network architectures and routing.