PID Controller Implementation
Overview
A PID (Proportional-Integral-Derivative) controller is a feedback control mechanism used in industrial control systems. It continuously calculates an error value and applies a correction based on proportional, integral, and derivative terms.
Control Law
output = Kp * error + Ki * integral(error) + Kd * derivative(error)
Where:
error= setpoint - measured_valueKp= proportional gain (reacts to current error)Ki= integral gain (reacts to accumulated error)Kd= derivative gain (reacts to the rate of change)
The implementation below takes the derivative of the filtered measurement instead of the error: -Kd * d(y_f)/dt. For a constant setpoint this equals the error derivative, but a setpoint step no longer produces a derivative kick.
Discrete-Time Implementation
import math
class PIDController:
def __init__(self, kp, ki, kd, output_min=None, output_max=None, n_filter=10.0):
self.kp = kp
self.ki = ki
self.kd = kd
self.output_min = -math.inf if output_min is None else output_min
self.output_max = math.inf if output_max is None else output_max
self.n_filter = n_filter # derivative filter time constant Tf = Td / N, Td = kd / kp
self.reset()
def reset(self):
"""Clear controller state."""
self.integral = 0.0
self.d_filtered = 0.0
self.prev_measurement = None # None until the first sample: no startup derivative spike
def compute(self, setpoint, measurement, dt):
"""Compute control output from setpoint, measurement, and timestep."""
error = setpoint - measurement
# Proportional term
p_term = self.kp * error
# Derivative on measurement with a first-order low-pass filter
if self.prev_measurement is not None and dt > 0:
raw = (measurement - self.prev_measurement) / dt
tf = (self.kd / self.kp) / self.n_filter if self.kp else 0.0
self.d_filtered += dt / (tf + dt) * (raw - self.d_filtered)
self.prev_measurement = measurement
d_term = -self.kd * self.d_filtered
# Integral term with anti-windup: the integral grows only up to the actuator
# headroom left by P + D, so the output still reaches its limit but never winds past it
base = p_term + d_term
i_old = self.ki * self.integral
i_term = self.ki * (self.integral + error * dt)
if base + i_term > self.output_max and i_term > i_old:
i_term = min(i_term, max(i_old, self.output_max - base))
elif base + i_term < self.output_min and i_term < i_old:
i_term = max(i_term, min(i_old, self.output_min - base))
if self.ki:
self.integral = i_term / self.ki
# Total output, clamped to the actuator range
output = base + i_term
return min(max(output, self.output_min), self.output_max)
Anti-Windup
Integral windup occurs when the output saturates but the integral keeps accumulating. Solutions:
- Integral clamping to headroom (used above): when the output would saturate, let the integral grow only until P + I + D reaches the limit. Rejecting the whole update instead can leave the output short of the limit indefinitely
- Back-calculation: integrate
error + (u_clamped - u_unsat) / (ki * Tt)instead oferror, with tracking time Tt between Ti and Td (often sqrt(Ti * Td)); the integral bleeds off while the output is clamped - Integral clamping: limit the integral term to the output range; simplest, but slower to recover
Setpoint Weighting and Bumpless Transfer
- Setpoint weighting: use
kp * (b * setpoint - measurement)for the proportional term with0 <= b <= 1to reduce overshoot after setpoint steps without slowing disturbance rejection. The derivative above already uses weight 0 on the setpoint; the integral must keep the full error for zero offset. - Bumpless transfer: when switching from manual to automatic, or changing gains online, set the integral so the controller output equals the current actuator value:
integral = (u_current - p_term - d_term) / ki. Also setprev_measurementto the current measurement so the derivative starts from zero.
Tuning Guidelines
Manual Tuning:
- Set Ki = Kd = 0
- Increase Kp until acceptable response speed
- Add Ki to eliminate steady-state error
- Add Kd to reduce overshoot
Effect of Each Gain:
- Higher Kp -> faster response, more overshoot
- Higher Ki -> eliminates steady-state error, can cause oscillation
- Higher Kd -> reduces overshoot, sensitive to noise