1
+ """PID controller
2
+
3
+ A minimal PID controller.
4
+
5
+ Example usage:
6
+ from tinypid import pid
7
+
8
+ controller = pid.PID()
9
+
10
+ output = controller(10)
11
+
12
+ """
1
13
from typing import Optional , Tuple
2
14
3
15
@@ -95,7 +107,9 @@ def limit(self, output: float) -> Tuple[bool, float]:
95
107
96
108
return saturated , output
97
109
98
- def __call__ (self , process_variable : float , manual_output : Optional [float ] = None , anti_windup : bool = True ) -> float :
110
+ def __call__ (
111
+ self , process_variable : float , manual_output : Optional [float ] = None , anti_windup : bool = True
112
+ ) -> float :
99
113
"""
100
114
Process the input signal and return the controller output.
101
115
@@ -110,9 +124,7 @@ def __call__(self, process_variable : float, manual_output: Optional[float] = No
110
124
111
125
self .P = self .K_p * error
112
126
self .I = self .K_i * self .integral
113
- self .D = self .K_d * (
114
- self .alpha * derivative + (1 - self .alpha ) * self ._previous_derivative
115
- )
127
+ self .D = self .K_d * (self .alpha * derivative + (1 - self .alpha ) * self ._previous_derivative )
116
128
117
129
output = self .P + self .I + self .D
118
130
@@ -127,12 +139,14 @@ def __call__(self, process_variable : float, manual_output: Optional[float] = No
127
139
128
140
if manual_output :
129
141
# Use setpoint tracking by calculating integral so that the output matches the manual setpoint
130
- self .integral = - (self .P + self .D - manual_output ) / self .K_i
142
+ self .integral = - (self .P + self .D - manual_output ) / self .K_i if self . K_i != 0 else 0
131
143
output = manual_output
132
144
133
145
return output
134
146
135
147
def __repr__ (self ):
136
- return (f"PID controller\n Setpoint: { self .setpoint } , Output: { self .P + self .I + self .D } \n "
137
- f"P: { self .P } , I: { self .I } , D: { self .D } \n " \
138
- f"Limits: { self .lower_limit } < output < { self .upper_limit } " )
148
+ return (
149
+ f"PID controller\n Setpoint: { self .setpoint } , Output: { self .P + self .I + self .D } \n "
150
+ f"P: { self .P } , I: { self .I } , D: { self .D } \n "
151
+ f"Limits: { self .lower_limit } < output < { self .upper_limit } "
152
+ )
0 commit comments