-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpid.py
More file actions
52 lines (40 loc) · 1.09 KB
/
pid.py
File metadata and controls
52 lines (40 loc) · 1.09 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
# import necessary packages
import time
class PID:
def __init__(self, kP=1, kI=0, kD=0):
# initialize gains
self.kP = kP
self.kI = kI
self.kD = kD
def initialize(self):
# intialize the current and previous time
self.currTime = time.time()
self.prevTime = self.currTime
# initialize the previous error
self.prevError = 0
# initialize the term result variables
self.cP = 0
self.cI = 0
self.cD = 0
def update(self, error, sleep = 0.1):
# pause for a bit
time.sleep(sleep)
# grab the current time and calculate delta time
self.currTime = time.time()
deltaTime = self.currTime - self.prevTime
# delta error
deltaError = error - self.prevError
# proportional term
self.cP = error
# integral term
self.cI += error * deltaTime * 4
# derivative term and prevent divide by zero
self.cD = (deltaError / deltaTime) if deltaTime > 0 else 0
# save previous time and error for the next update
self.prevTime = self.currTime
self.prevError = error
# sum the terms and return
return sum([
self.kP * self.cP,
self.kI * self.cI,
self.kD * self.cD])