Skip to content

Instantly share code, notes, and snippets.

@hax0kartik
Created March 23, 2025 09:23
Show Gist options
  • Save hax0kartik/c5b5a598e91a80c65459962ef4180cad to your computer and use it in GitHub Desktop.
Save hax0kartik/c5b5a598e91a80c65459962ef4180cad to your computer and use it in GitHub Desktop.
class PIDController:
def __init__(self, Kp, Ki, Kd, setpoint, dt, output_bias, output_limits=(None, None)):
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.setpoint = setpoint
self.dt = dt
self.output_min, self.output_max = output_limits
self.integral = 0.0
self.prev_pv = 0.0 # Previous process variable
self.output_bias = output_bias
def compute(self, process_variable):
pv = process_variable["Port Primary Weld Current"] + process_variable["Starboard Primary Weld Current"]
displacement_index = int(process_variable["Displacement Index"])
# Proportional term
if 36 < displacement_index:
displacement_index = 36
error = self.setpoint - (pv)
# Proportional term
proportional = self.Kp.iloc[displacement_index]["Kp"] * error
# Derivative term (using PV to avoid derivative kick)
derivative = -self.Kd.iloc[displacement_index]["Kd"] * (pv - self.prev_pv) / self.dt
# Calculate raw output
raw_output = proportional + self.integral + derivative + self.output_bias
# Clamp the output
output = raw_output
clamped = False
if self.output_min is not None and output < self.output_min:
output = self.output_min
clamped = True
elif self.output_max is not None and output > self.output_max:
output = self.output_max
clamped = True
# Update integral only if not clamped
if not clamped:
self.integral += self.Ki * error * self.dt
# Save current PV for next derivative calculation
self.prev_pv = pv
return output
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment