Your PID controller implementation is well-structured, but I see several potential issues that could cause problems in real-world usage:
Issues and Improvements:
1. Integral Anti-Windup Problem
# Current implementation
self.integral = max(-5, min(5, self.integral)) # Fixed range
# Better approach - base on output range
max_integral = (self.mv_max - self.mv_min) / self.Ki if self.Ki != 0 else 5
self.integral = max(-max_integral, min(max_integral, self.integral))
2. Missing Output Saturation Handling
When mv hits limits, the integral should stop accumulating:
# Add after calculating new mv
if self.mv == self.mv_min or self.mv == self.mv_max:
# Prevent integral windup when output is saturated
if (error > 0 and self.mv == self.mv_max) or (error < 0 and self.mv == self.mv_min):
self.integral -= error * self.sample_interval # Undo the accumulation
3. Derivative Kick Protection
Current implementation suffers from "derivative kick" when setpoint changes:
# Instead of using error derivative, use PV derivative
def get_new_mv(self, setpoint, actual):
error = setpoint - actual
# ... p_term and i_term calculations ...
# Derivative on measurement (prevents derivative kick)
derivative = (self.last_pv - actual) / self.sample_interval if hasattr(self, 'last_pv') else 0
d_term = self.Kd * derivative
self.last_pv = actual # Store process variable instead of error
4. Incomplete Self-Tuning Logic
def is_oscillating(self):
"""Improved oscillation detection"""
if len(self.recent_adjustments) < 6:
return False
# Check for sustained oscillations, not just sign changes
crossings = 0
mean_adj = sum(self.recent_adjustments[-10:]) / min(10, len(self.recent_adjustments))
for i in range(1, min(10, len(self.recent_adjustments))):
if ((self.recent_adjustments[-i] - mean_adj) *
(self.recent_adjustments[-i-1] - mean_adj)) < 0:
crossings += 1
return crossings > 6 and abs(mean_adj) < 0.1 # Oscillating around mean
# Also add gain recovery
if not self.is_oscillating() and len(self.recent_adjustments) > 20:
# Slowly increase gains if system is stable
if self.Kp < 0.5: # Original value
self.Kp *= 1.01
if self.Ki < 0.1:
self.Ki *= 1.01
5. Missing Reset Functionality
def reset(self, new_mv=None):
"""Reset controller state for new control session"""
self.integral = 0
self.last_error = 0
self.last_pv = None
self.recent_adjustments = []
if new_mv is not None:
self.mv = max(self.mv_min, min(self.mv_max, new_mv))