forked from dev-moo/thermostat
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpid_control.py
executable file
·94 lines (53 loc) · 1.62 KB
/
pid_control.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
#!/usr/bin/python
import random
import datetime
from time import sleep
class PID_Controller(object):
def Compute(self):
error = 0
dInput = 0
now = datetime.datetime.now()
timeChange = now - self.lastTime
timeChange = timeChange.total_seconds()
#if timeChange >= self.SampleTime:
error = self.Setpoint - self.Input
self.ITerm += self.ki * error
if self.ITerm > self.outMax:
self.ITerm = self.outMax
elif self.ITerm < self.outMin:
self.ITerm = self.outMin
dInput = self.Input - self.lastInput
self.Output = self.kp * error + self.ITerm - self.kd * dInput
print str(self.Output) + ' = ' + str(self.kp) + ' * ' + str(error) + ' + ' + str(self.ITerm) + ' - ' + str(self.kd) + ' * ' + str(dInput)
print "Calculated output: " + str(self.Output)
if self.Output > self.outMax:
self.Output = self.outMax
elif self.Output < self.outMin:
self.Output = self.outMin
self.lastInput = self.Input
self.lastTime = datetime.datetime.now()
def SetTunings(self, KP, KI, KD):
self.kp = KP
self.ki = KI
self.kd = KD
def __init__(self, sp, ct):
self.lastTime = datetime.datetime.now()
self.Setpoint = sp
self.Input = ct
self.Output = ct
self.ITerm = ct
self.lastInput = ct
self.kp = 2.1
self.ki = 0.5
self.kd = 2
self.SampleTime = 1
self.outMin = 18
self.outMax = 34
def update(self, newInput):
print 'Input: ' + str(newInput)
self.Input = newInput
self.Compute()
print 'Output: ' + str(self.Output)
return float(self.Output)
if __name__ == "__main__":
PID = PID_Controller(25, 25)