|
PID Controller Tutorial
This interactive tutorial demonstrates the PID (Proportional-Integral-Derivative) Controller algorithm, a fundamental feedback control technique widely used in industrial automation, robotics, aerospace, and process control systems. A PID controller is a feedback control system that continuously calculates an error value (difference between desired setpoint and current process value) and applies a correction based on proportional, integral, and derivative terms. The controller's goal is to minimize the error over time by adjusting the control output to bring the process value to the desired setpoint.
The visualization consists of four interactive system types: (1) Heating System - simulates temperature control (like an oven or heater), where the controller adjusts heating power to reach a target temperature, (2) Mass-Spring System - simulates position control (like a servo motor or robotic arm), where the controller applies force to move a mass to a target position, (3) Water Tank - simulates fluid level control with inflow and outflow dynamics, and (4) Cruise Control - simulates vehicle speed control with drag resistance. The visualization uses HTML5 Canvas for real-time rendering, a dark theme (black background) with bright colors for optimal visibility (green for setpoint, red for process value). You can adjust the PID gains (Kp, Ki, Kd) using sliders (Kp: 0-30, Ki: 0-15, Kd: 0-6) to see how each term affects the controller's response. The setpoint can be changed dynamically, and the real-time graph shows how the process value tracks the setpoint over time, demonstrating key control concepts like overshoot, settling time, steady-state error, and stability.
The simulator includes an Auto-Tune feature that uses the Relay Method (Åström–Hägglund method) to automatically determine optimal PID parameters. When activated, the system temporarily switches to bang-bang (on/off) control to force stable oscillation, detects oscillation peaks, and calculates optimal Kp, Ki, and Kd values using Ziegler-Nichols formulas. The auto-tune feature updates sliders in real-time as peaks are detected (after 2 peaks) and completes when the oscillation is stable and near the setpoint. You can adjust the "Auto Tune Setpoint Tolerance" parameter (0-10%, default: 2%) to control how close the oscillation must be to the setpoint before completion.
The PID controller operates by computing three terms based on the error: (1) Proportional (P) - responds to current error proportionally, (2) Integral (I) - accumulates past errors to eliminate steady-state offset, and (3) Derivative (D) - predicts future error based on rate of change to reduce overshoot. The controller output is the sum of these three terms: u(t) = Kpe(t) + Ki∫e(t)dt + Kdde/dt. The gains (Kp, Ki, Kd) determine how much each term contributes to the output. Tuning these gains is the key skill in PID control - higher Kp gives faster response but may cause overshoot, higher Ki eliminates steady-state error but may cause instability, and higher Kd reduces overshoot but may amplify noise. The tutorial includes anti-windup protection to prevent integral term from accumulating when the output is saturated, which is essential for stable real-world control.
NOTE : The tutorial uses standard PID controller notation: SP (Setpoint - desired value), PV (Process Value - current measured value), e(t) (Error = SP - PV), Kp (Proportional Gain), Ki (Integral Gain), Kd (Derivative Gain), and u(t) (Control Output). The controller implementation follows the standard PID algorithm: u(t) = Kpe(t) + Ki∫e(t)dt + Kdde/dt with anti-windup protection to prevent integral saturation when output limits are reached.
Mathematical Model
A PID controller is a feedback control mechanism that continuously calculates an error value as the difference between a desired setpoint (SP) and a measured process variable (PV), and applies a correction based on proportional, integral, and derivative terms.
PID Controller Equation:
u(t) = Kpe(t) + Ki∫0te(τ)dτ + Kd(de/dt)
where:
- u(t): Control output at time t
- e(t) = SP - PV: Error (difference between setpoint and process value)
- Kp: Proportional gain (response to current error)
- Ki: Integral gain (eliminates steady-state error)
- Kd: Derivative gain (reduces overshoot and oscillations)
Discrete-Time Implementation:
P(t) = Kp × e(t) (Proportional Term)
I(t) = I(t-1) + Ki × e(t) × dt (Integral Term - accumulated)
D(t) = Kd × (e(t) - e(t-1)) / dt (Derivative Term - rate of change)
u(t) = P(t) + I(t) + D(t) (Total Output)
Term Interpretation: The Proportional (P) term responds immediately to the current error - larger error produces larger output. This gives fast response but alone cannot eliminate steady-state error. The Integral (I) term accumulates past errors over time - it continues to increase until the error becomes zero, eliminating any steady-state offset. However, integral action can cause overshoot and instability if too large. The Derivative (D) term predicts future error based on the rate of change - if the error is decreasing rapidly, it reduces the output to prevent overshoot. This dampens oscillations but can amplify noise.
Heating System: In this mode, we control the temperature of a heating element. The system has thermal inertia - it takes time to heat up or cool down. The process is modeled as a first-order system with time constant τ: dT/dt = (1/τ)(Tambient + controlSignal - T). When the setpoint increases, the PID controller increases heating power, and the temperature gradually rises toward the setpoint. You can observe how different gain combinations affect the response: high Kp causes fast rise but may overshoot, high Ki eliminates steady-state error (perfect tracking), and high Kd reduces overshoot.
Mass-Spring System: In this mode, we control the position of a mass connected to a spring. The system has mechanical dynamics with inertia, spring force, and damping. The process is modeled as a second-order system: F = ma = u(t) - kx - cv, where k is spring constant, c is damping, x is position, and v is velocity. When the setpoint changes, the PID controller applies force to move the mass to the target position. You can observe how different gain combinations affect the response: high Kp gives strong response but may oscillate, high Ki eliminates steady-state error but may cause overshoot, and high Kd provides damping to reduce oscillations.
Water Tank System: In this mode, we control the water level in a tank. The system has fluid dynamics with inflow from a valve and outflow through a drain. The process is modeled as: dh/dt = (FlowIn - FlowOut) / Area, where FlowIn is controlled by valve opening (0-100%), and FlowOut depends on water height (pressure-driven). When the setpoint changes, the PID controller adjusts the valve opening to reach the target level. This system demonstrates first-order dynamics with delayed response due to tank capacity.
Cruise Control System: In this mode, we control the speed of a vehicle. The system has mechanical dynamics with engine force and drag resistance. The process is modeled as: F = ma = EngineForce - Drag, where drag increases with speed. When the setpoint changes, the PID controller adjusts throttle force to reach the target speed. This system demonstrates how drag creates nonlinear dynamics and steady-state behavior.
Auto-Tune Feature: The simulator includes an automatic tuning feature that uses the Relay Method (Åström–Hägglund method) to determine optimal PID parameters. When activated, the system temporarily switches to bang-bang control to force stable oscillation around the setpoint. The auto-tune algorithm detects oscillation peaks, calculates the ultimate period (Tu) and ultimate gain (Ku), then applies Ziegler-Nichols formulas to compute optimal Kp, Ki, and Kd values. The sliders update in real-time as peaks are detected (after 2 peaks), and auto-tune completes when the oscillation is stable (periods within 20% of each other) and near the setpoint (within user-defined tolerance). Auto-tune parameters include: (1) "Auto Tune Delay" - controls animation speed during tuning (0-200 ms), and (2) "Auto Tune Setpoint Tolerance" - controls how close oscillation must be to setpoint before completion (0-10% of setpoint, default: 2%).
Usage Example
Follow these steps to explore the PID Controller tutorial:
-
Initial State (Heating System): When you first load the simulation, you'll see the Heating System mode active. The system starts at ambient temperature (20°C) with a setpoint of 30°C. The PID controller begins applying heating power to reach the target temperature. Click "Start" to begin the simulation - watch as the red line (process value - temperature) rises toward the green line (setpoint) over time. The system visualization shows a temperature gauge with a needle indicating current temperature and a green marker showing the setpoint.
-
Adjust PID Gains: Use the Kp, Ki, and Kd sliders to adjust the controller gains. Try different combinations to see how each term affects the response: (1) High Kp (e.g., 5.0) - fast response but may overshoot, (2) High Ki (e.g., 1.0) - eliminates steady-state error but may cause overshoot, (3) High Kd (e.g., 0.5) - reduces overshoot but may amplify noise. Notice how the process value response changes as you adjust each gain.
-
Try Preset Configurations: Use the "Preset" dropdown to select pre-configured gain combinations: (1) Aggressive - fast response with overshoot, (2) Moderate - balanced performance, (3) Conservative - smooth and stable, (4) No Overshoot - slow but stable, (5) Quick Response - P-dominant for fast response, (6) Integral Heavy - zero steady-state error focus. Compare how each preset affects the system response.
-
Switch System Types: Use the "System Type" dropdown to switch between different systems: (1) Heating System - first-order thermal system with time constant, (2) Mass-Spring System - second-order mechanical system with spring and damping, (3) Water Tank - fluid level control with inflow/outflow dynamics, (4) Cruise Control - vehicle speed control with drag resistance. Each system demonstrates different dynamics and requires different tuning strategies.
-
Adjust Setpoint: Use the "Setpoint" slider to change the target value (0-50). Watch how the controller responds to setpoint changes. Try step changes (sudden setpoint changes) to observe transient response characteristics like rise time, overshoot, settling time, and steady-state error. Notice how different gain combinations affect these metrics.
-
Use Auto-Tune Feature: Click the "Auto-Tune Start" button to activate automatic parameter tuning. The system will temporarily switch to bang-bang control to force stable oscillation. Watch as the system oscillates around the setpoint - the sliders will update in real-time as peaks are detected (after 2 peaks). Auto-tune completes when the oscillation is stable and near the setpoint. The calculated Kp, Ki, and Kd values are automatically applied. You can adjust "Auto Tune Delay" (0-200 ms) to control animation speed and "Auto Tune Setpoint Tolerance" (0-10%, default: 2%) to control how close the oscillation must be to the setpoint.
-
Observe Real-time Updates: During auto-tune, watch the sliders update in real-time as peaks are detected. The system calculates optimal parameters using Ziegler-Nichols formulas based on the oscillation period and amplitude. Notice how the calculated values change as more peaks are detected, providing increasingly accurate tuning results.
-
Reset and Experiment: Click the "Reset" button to reset the system to its initial state and restore default PID parameters (Kp=1.0, Ki=0.1, Kd=0.05). Try different system types, setpoints, and tuning strategies to understand how PID control works across different applications. Compare manual tuning versus auto-tune results.
-
Understand Control Concepts: Observe key control performance metrics: (1) Overshoot - how much the process value exceeds the setpoint, (2) Settling Time - how long it takes to reach and stay within tolerance, (3) Steady-State Error - persistent offset from setpoint (eliminated by integral term), (4) Stability - whether the system converges or oscillates. Different gain combinations affect these metrics differently.
-
Compare System Responses: Switch between system types and compare how they respond to the same PID settings. Notice that Heating System (first-order) is simpler and easier to tune than Mass-Spring System (second-order) which may oscillate. Water Tank shows fluid dynamics with time delays, and Cruise Control shows nonlinear behavior due to drag. Each system requires different tuning strategies.
Tip: The key to understanding PID control is recognizing how each term (Proportional, Integral, Derivative) affects the system response. Start with moderate gains and adjust one parameter at a time to see its effect. Use auto-tune as a starting point, then fine-tune manually if needed. Observe the time-domain response (overshoot, settling time, steady-state error) to evaluate tuning quality. Higher gains generally give faster response but may cause instability. Lower gains are more stable but may be too slow. The optimal balance depends on the specific application requirements. Auto-tune provides a good starting point by automatically finding gains that create stable oscillation, then calculating optimal values using proven formulas.
Parameters
Followings are short descriptions on each parameter
-
Proportional Gain (Kp): Controls the response to current error. Kp is multiplied by the error (difference between setpoint and process value) to produce the proportional term. Higher Kp gives faster response but may cause overshoot and oscillations. Lower Kp gives slower but more stable response. Range: 0-30. Default: 1.0. The proportional term responds immediately to error changes but cannot eliminate steady-state error alone.
-
Integral Gain (Ki): Controls the accumulation of past errors to eliminate steady-state error. Ki is multiplied by the integral of error over time. Higher Ki eliminates steady-state error faster but may cause overshoot and instability. Lower Ki provides smoother response but may leave residual error. Range: 0-15. Default: 0.1. The integral term accumulates errors until they become zero, ensuring perfect tracking at steady-state. Anti-windup protection prevents integral saturation when output limits are reached.
-
Derivative Gain (Kd): Controls the response to rate of change of error to reduce overshoot and oscillations. Kd is multiplied by the derivative (rate of change) of error. Higher Kd provides more damping to reduce overshoot but may amplify noise. Lower Kd reduces noise sensitivity but may allow more overshoot. Range: 0-6. Default: 0.05. The derivative term predicts future error based on current rate of change, providing damping to stabilize the system.
-
Setpoint (SP): The desired target value for the process variable. The controller's goal is to bring the process value (PV) to match the setpoint. Range: 0-50. Default: 30.0. The setpoint can be adjusted dynamically during operation. When the setpoint changes, the controller responds by adjusting the output to bring the process value to the new target.
-
Process Value (PV): The current measured value of the controlled variable (temperature, position, level, speed depending on system type). The controller compares PV to SP to calculate error: e(t) = SP - PV. The controller adjusts output to minimize this error over time.
-
Error (e): The difference between setpoint and process value: e(t) = SP - PV. The controller uses this error to calculate the three PID terms. When PV < SP, error is positive (controller increases output). When PV > SP, error is negative (controller decreases output). When PV = SP, error is zero (steady-state achieved).
-
Control Output (u): The calculated control signal sent to the system. The output is the sum of three terms: u(t) = Kp·e(t) + Ki·∫e(t)dt + Kd·de/dt. The output is clamped to limits (-1000 to +1000 units) to prevent saturation. The system responds to this output based on its physics (heating power, force, valve opening, throttle force).
-
System Type: The physical system being controlled. Four system types are available: (1) Heating System - first-order thermal system with time constant, (2) Mass-Spring System - second-order mechanical system with spring and damping, (3) Water Tank - fluid level control with inflow/outflow dynamics, (4) Cruise Control - vehicle speed control with drag resistance. Each system has different dynamics and requires different tuning strategies.
-
Auto Tune Delay: Animation delay during auto-tune operation (milliseconds). Range: 0-200 ms. Default: 100 ms. Lower values make auto-tune run faster but may be harder to observe. Higher values slow down animation for better visualization. This parameter does not affect the tuning calculations, only the animation speed.
-
Auto Tune Setpoint Tolerance: Maximum deviation from setpoint (as percentage of setpoint) required for auto-tune to complete. Range: 0-10%. Default: 2%. Auto-tune will only finish when the oscillation center (average of last 3 peaks) is within this tolerance of the setpoint. Lower values require oscillation to be very close to setpoint before completion (stricter). Higher values allow oscillation further from setpoint (more lenient). Uses absolute tolerance of 2.0 units minimum for small setpoints.
-
Step Delay: Animation delay for normal simulation (milliseconds). Range: 0-200 ms. Default: 0 ms. Controls the speed of the simulation. When set to 0, the simulation runs at maximum speed (multiple steps per frame). Higher values slow down the simulation for easier observation. This parameter does not affect the physics calculations, only the animation speed.
Controls and Visualizations
Followings are short descriptions on each control
-
System Type Selector: Dropdown menu to select the system being controlled. Options: (1) Heating System - first-order thermal system, (2) Mass-Spring System - second-order mechanical system, (3) Water Tank - fluid level control, (4) Cruise Control - vehicle speed control. Each system has different dynamics and visualizations. Changing system type automatically resets the simulation to initial conditions.
-
Preset Selector: Dropdown menu to select pre-configured PID gain combinations. Options: (1) Aggressive - fast response with overshoot (Kp=3.0, Ki=0.5, Kd=0.2), (2) Moderate - balanced performance (Kp=1.5, Ki=0.2, Kd=0.1), (3) Conservative - smooth and stable (Kp=0.8, Ki=0.1, Kd=0.05), (4) No Overshoot - slow but stable (Kp=0.5, Ki=0.15, Kd=0.3), (5) Quick Response - P-dominant (Kp=4.0, Ki=0.1, Kd=0.15), (6) Integral Heavy - zero steady-state error focus (Kp=1.0, Ki=1.0, Kd=0.05), (7) Custom - manual adjustment. Selecting a preset automatically updates sliders and PID controller.
-
Kp Slider: Adjusts Proportional Gain (0-30, default: 1.0). Higher Kp gives faster response but may cause overshoot. Lower Kp gives slower but more stable response. The slider updates the PID controller in real-time. Adjusting any slider automatically sets preset to "Custom".
-
Ki Slider: Adjusts Integral Gain (0-15, default: 0.1). Higher Ki eliminates steady-state error faster but may cause overshoot. Lower Ki provides smoother response. The slider updates the PID controller in real-time. The integral term accumulates errors until they become zero.
-
Kd Slider: Adjusts Derivative Gain (0-6, default: 0.05). Higher Kd provides more damping to reduce overshoot but may amplify noise. Lower Kd reduces noise sensitivity but may allow more overshoot. The slider updates the PID controller in real-time.
-
Setpoint Slider: Adjusts the target value (0-50, default: 30.0). The controller's goal is to bring the process value to match the setpoint. The setpoint can be changed dynamically during operation. Changing setpoint creates a step change that demonstrates transient response (rise time, overshoot, settling time).
-
Step Delay Slider: Controls animation speed for normal simulation (0-200 ms, default: 0 ms). When set to 0, simulation runs at maximum speed. Higher values slow down animation for easier observation. Does not affect physics calculations, only animation speed.
-
Auto Tune Delay Slider: Controls animation speed during auto-tune (0-200 ms, default: 100 ms). Lower values make auto-tune run faster. Higher values slow down for better visualization. Does not affect tuning calculations, only animation speed.
-
Auto Tune Setpoint Tolerance Slider: Controls how close oscillation must be to setpoint for auto-tune to complete (0-10%, default: 2%). Lower values require oscillation very close to setpoint (stricter). Higher values allow oscillation further from setpoint (more lenient). Uses absolute tolerance of 2.0 units minimum for small setpoints.
-
Start/Pause Button: Toggles simulation execution. Click "Start" to begin simulation or resume from pause. Click "Pause" to stop simulation temporarily. The simulation continues from where it paused when resumed.
-
Reset Button: Resets the system to initial conditions and restores default PID parameters (Kp=1.0, Ki=0.1, Kd=0.05). Clears all history and restarts the simulation from time t=0. Also resets sliders to default values. Stops auto-tune if active.
-
Auto-Tune Start/Stop Button: Toggles automatic parameter tuning. Click "Auto-Tune Start" to begin auto-tune - the system switches to relay (bang-bang) control to force oscillation. Sliders update in real-time as peaks are detected (after 2 peaks). Auto-tune completes automatically when oscillation is stable and near setpoint, or click "Auto-Tune Stop" to stop manually. Button changes to "Auto-Tune Stop" during tuning with orange background.
-
System View Canvas: Real-time visualization of the controlled system. (1) Heating System - Temperature gauge with needle (red) showing current temperature and green marker showing setpoint, (2) Mass-Spring System - Animated block connected to spring with position visualization, (3) Water Tank - Filling tank with blue water and green setpoint marker, (4) Cruise Control - Scrolling road with car and speedometer display (km/h). Visualizations update in real-time as the system responds to control.
-
Time Series Graph: Real-time plot showing Setpoint (SP - green line) and Process Value (PV - red line) over time. Time progresses from left to right, starting at t=0. Values are plotted vertically (range: 0-50). The graph demonstrates key control concepts: rise time, overshoot, settling time, steady-state error, and stability. History is kept from t=0 (no scrolling/limiting).
-
Block Diagram: Interactive PID controller block diagram drawn with Canvas API. Shows the control loop: Setpoint → Sum → Split → P/I/D Blocks → Sum → Process → Output → Feedback (negative). Uses standard colors: Yellow (P), Green (I), Orange (D), Dark Green (Process). Demonstrates the PID controller structure and signal flow.
-
Info Display: Real-time display showing: System Type, Current Value (PV), Setpoint (SP), Error (SP - PV), and Control Output. Updates continuously during simulation to show current state values.
Key Concepts
-
Proportional Control: The P term responds immediately to current error. Higher Kp gives faster response but may cause overshoot and oscillations. The P term alone cannot eliminate steady-state error - if the system needs a constant output to maintain setpoint, the P term alone cannot provide it (error must be zero, which means output is zero). This is why integral action is needed for perfect tracking.
-
Integral Control: The I term accumulates past errors over time, eliminating steady-state error. The integral term continues to increase until error becomes zero, ensuring perfect tracking at steady-state. However, integral action can cause overshoot and instability if too large. Anti-windup protection prevents integral saturation when output limits are reached, which is essential for stable real-world control.
-
Derivative Control: The D term responds to the rate of change of error, providing damping to reduce overshoot and oscillations. The derivative term predicts future error based on current rate of change - if error is decreasing rapidly, it reduces output to prevent overshoot. However, derivative action amplifies noise, so it must be used carefully. High-frequency noise can cause excessive output variations if Kd is too large.
-
Tuning Trade-offs: PID tuning involves balancing competing objectives: (1) Fast Response - higher gains give faster response but may cause overshoot, (2) Stability - lower gains are more stable but may be too slow, (3) Steady-State Error - integral action eliminates offset but may cause overshoot, (4) Noise Sensitivity - derivative action reduces overshoot but amplifies noise. The optimal balance depends on application requirements.
-
System Dynamics: Different system types have different dynamics: (1) First-Order Systems (Heating, Water Tank) - simpler dynamics, easier to tune, single time constant, (2) Second-Order Systems (Mass-Spring) - more complex dynamics with oscillation modes, requires damping, (3) Nonlinear Systems (Cruise Control) - drag creates nonlinear behavior, may require adaptive tuning. Understanding system dynamics helps select appropriate tuning strategies.
-
Auto-Tune Algorithm: The auto-tune feature uses the Relay Method (Åström–Hägglund method), an industry-standard auto-tuning technique. It temporarily switches to bang-bang control to force stable oscillation, measures oscillation period (Tu) and amplitude, then calculates Ultimate Gain (Ku) using: Ku = (4·d) / (π·a), where d is relay amplitude and a is oscillation amplitude. Ziegler-Nichols formulas are then applied: Kp = 0.6·Ku, Ki = (2·Kp)/Tu, Kd = (Kp·Tu)/8. Auto-tune includes safety features: period clamping (minimum 0.05s), Ku limiting (maximum 100), and parameter clamping to prevent explosion.
-
Stability: A stable controller converges to the setpoint without oscillations or instability. Stability depends on gain values relative to system dynamics. High gains may cause instability (oscillations, overshoot). Low gains are stable but may be too slow. The optimal gains provide fast response with acceptable overshoot and no steady-state error. Auto-tune calculates gains that provide stable control based on measured system dynamics.
-
Transient Response: Key performance metrics include: (1) Rise Time - time to reach setpoint from 10% to 90% of step, (2) Overshoot - maximum amount process value exceeds setpoint, (3) Settling Time - time to reach and stay within tolerance (typically ±2%), (4) Steady-State Error - persistent offset from setpoint (eliminated by integral action), (5) Peak Time - time to reach maximum overshoot. These metrics help evaluate tuning quality.
-
Applications: PID controllers are used in numerous applications: (1) Temperature Control - ovens, heaters, HVAC systems, (2) Motion Control - servo motors, robotic arms, CNC machines, (3) Level Control - tanks, reservoirs, chemical processes, (4) Speed Control - vehicles, motors, turbines, (5) Pressure Control - compressors, flow systems, (6) Process Control - chemical plants, manufacturing, (7) Aerospace - attitude control, altitude hold. PID control is the most widely used control algorithm in industry.
-
Anti-Windup: Integral saturation occurs when output is limited (clamped to min/max) but integral term continues to accumulate error. This causes overshoot when setpoint changes or limits are removed. Anti-windup protection prevents integral accumulation when output is saturated, improving transient response. The simulator implements clamping anti-windup - when integral term would exceed limits, it is clamped to prevent excessive accumulation.
-
Manual Tuning Strategies: Common manual tuning approaches: (1) Ziegler-Nichols - find ultimate gain and period, apply formulas (same as auto-tune), (2) Trial and Error - start with low gains, increase until oscillation, then reduce, (3) Process Reaction Curve - measure step response, estimate time constant and dead time, apply formulas, (4) IMC (Internal Model Control) - model-based tuning for better performance, (5) Lambda Tuning - specify closed-loop time constant, calculate gains. Auto-tune automates the Ziegler-Nichols method.
-
Real-Time Parameter Updates: During auto-tune, sliders update in real-time as peaks are detected (after 2 peaks). This allows observation of how tuning parameters evolve as more oscillation data is collected. The final parameters are applied automatically when auto-tune completes, or can be applied manually when stopped. Parameters can be fine-tuned manually after auto-tune if needed.
|
|