Skip to content

Instantly share code, notes, and snippets.

@MagdielCAS
Created June 17, 2020 14:31
Show Gist options
  • Save MagdielCAS/1fcf8c0ae32c0408ac87c261f3e7afb3 to your computer and use it in GitHub Desktop.
Save MagdielCAS/1fcf8c0ae32c0408ac87c261f3e7afb3 to your computer and use it in GitHub Desktop.
An simple class to compute pid with ajustable parameters
class PID:
def __init__(
self,
Kp = 10,
Ki = 1,
Kd = 1,
N = 20,
Ts = 0.01,
):
#user-adjustable parameters
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.N = N
self.Ts = Ts
# computed parameters
self.a0 = (1+N*Ts)
self.a1 = -(2 + N*Ts)
self.a2 = 1
self.b0 = Kp*(1+N*Ts) + Ki*Ts*(1+N*Ts) + Kd*N
self.b1 = -(Kp*(2+N*Ts) + Ki*Ts + 2*Kd*N)
self.b2 = Kp + Kd*N
self.ku1 = self.a1/self.a0
self.ku2 = self.a2/self.a0
self.ke0 = self.b0/self.a0
self.ke1 = self.b1/self.a0
self.ke2 = self.b2/self.a0
# global variables
##variables used in PID computation
self.e2 = 0.0
self.e1 = 0.0
self.e0 = 0.0
self.u2 = 0.0
self.u1 = 0.0
self.u0 = 0.0
self.r = 0.0 # command
def change_parameters(
self,
Kp = 10,
Ki = 1,
Kd = 1,
N = 20,
Ts = 0.01,
):
#user-adjustable parameters
self.Kp = Kp
self.Ki = Ki
self.Kd = Kd
self.N = N
self.Ts = Ts
def compute(self, y = 1):
self.e2=self.e1
self.e1=self.e0
self.u2=self.u1
self.u1=self.u0
self.e0 = self.r - y #compute new error
self.u0 = -self.ku1*self.u1 - self.ku2*self.u2 + self.ke0*self.e0 + self.ke1*self.e1 + self.ke2*self.e2 # pid discrete form
# if self.u0 > UMAX: self.u0 = UMAX #limit to DAC or PWM range
# if self.u0 < UMIN: self.u0 = UMIN
return self.u0
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment