Skip to content

Commit 7708d3c

Browse files
committed
Add PID controller implementation
1 parent 745bd2b commit 7708d3c

File tree

2 files changed

+14
-11
lines changed

2 files changed

+14
-11
lines changed

control_algorithms/__init__.py

Whitespace-only changes.

control_algorithms/pid.py

+14-11
Original file line numberDiff line numberDiff line change
@@ -1,16 +1,19 @@
11
"""
2-
A Proportional-Integral-Derivative (PID) controller is a control loop mechanism that calculates an error
3-
value as the difference between a desired setpoint and a measured process variable.
2+
A Proportional-Integral-Derivative (PID) controller
3+
is a control loop mechanism that calculates an error
4+
value as the difference between a desired setpoint
5+
and a measured process variable.
46
5-
It applies proportional, integral, and derivative corrections to minimize the error over time.
7+
It applies proportional, integral, and derivative
8+
corrections to minimize the error over time.
69
710
Refer - https://en.wikipedia.org/wiki/PID_controller
811
"""
912

1013

11-
class pid:
14+
class PID:
1215

13-
def __init__(self, Kp: float, Ki: float, Kd: float, setpoint: float = 0):
16+
def __init__(self, kp: float, ki: float, kd: float, setpoint: float = 0):
1417
"""
1518
Initialize the PID controller.
1619
@@ -19,9 +22,9 @@ def __init__(self, Kp: float, Ki: float, Kd: float, setpoint: float = 0):
1922
:param Kd: Derivative gain
2023
:param setpoint: Desired target value
2124
"""
22-
self.Kp = Kp
23-
self.Ki = Ki
24-
self.Kd = Kd
25+
self.kp = kp
26+
self.ki = ki
27+
self.kd = kd
2528
self.setpoint = setpoint
2629

2730
self.integral = 0
@@ -39,14 +42,14 @@ def compute(self, measured_value: float, dt: float) -> float:
3942
self.integral += error * dt if error != 0 else 0
4043
derivative = (error - self.previous_error) / dt if dt > 0 else 0
4144

42-
output = (self.Kp * error) + (self.Ki * self.integral) + (self.Kd * derivative)
45+
output = (self.kp * error) + (self.ki * self.integral) + (self.kd * derivative)
4346
self.previous_error = error
4447
return output
4548

4649
def reset(self):
4750
"""Reset the integral and previous error values."""
48-
self.integral = 0
49-
self.previous_error = 0
51+
self.integral = 0.0
52+
self.previous_error = 0.0
5053

5154

5255
if __name__ == "__main__":

0 commit comments

Comments
 (0)