forked from nebhead/PiFire
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpid.py
executable file
·99 lines (78 loc) · 2.45 KB
/
pid.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
95
96
97
98
99
#!/usr/bin/env python3
# *****************************************
# PiFire PID Controller
# *****************************************
#
# Description: This object will be used to calculate PID for maintaining
# temperature in the grill.
#
# This software was developed by GitHub user DBorello as part of his excellent
# PiSmoker project: https://github.com/DBorello/PiSmoker
#
# Adapted for PiFire
#
# PID controller based on proportional band in standard PID form https://en.wikipedia.org/wiki/PID_controller#Ideal_versus_standard_PID_form
# u = Kp (e(t)+ 1/Ti INT + Td de/dt)
# PB = Proportional Band
# Ti = Goal of eliminating in Ti seconds
# Td = Predicts error value at Td in seconds
# *****************************************
# *****************************************
# Imported Libraries
# *****************************************
import time
# *****************************************
# Class Definition
# *****************************************
class PID:
def __init__(self, pb, ti, td, center):
self._calculate_gains(pb,ti,td)
self.p = 0.0
self.i = 0.0
self.d = 0.0
self.u = 0
self.last_update = time.time()
self.error = 0.0
self.set_point = 0
self.center = center
self.derv = 0.0
self.inter = 0.0
self.inter_max = abs(self.center / self.ki)
self.last = 150
self.set_target(0.0)
def _calculate_gains(self, pb, ti, td):
self.kp = -1 / pb
self.ki = self.kp / ti
self.kd = self.kp * td
def update(self, current):
# P
error = current - self.set_point
self.p = self.kp * error + self.center # p = 1 for pb / 2 under set_point, p = 0 for pb / 2 over set_point
# I
dt = time.time() - self.last_update
# if self.p > 0 and self.p < 1: # Ensure we are in the pb, otherwise do not calculate i to avoid windup
self.inter += error * dt
self.inter = max(self.inter, -self.inter_max)
self.inter = min(self.inter, self.inter_max)
self.i = self.ki * self.inter
# D
self.derv = (current - self.last) / dt
self.d = self.kd * self.derv
# PID
self.u = self.p + self.i + self.d
# Update for next cycle
self.error = error
self.last = current
self.last_update = time.time()
return self.u
def set_target(self, set_point):
self.set_point = set_point
self.error = 0.0
self.inter = 0.0
self.derv = 0.0
self.last_update = time.time()
def set_gains(self, pb, ti, td):
self._calculate_gains(pb,ti,td)
self.inter_max = abs(self.center / self.ki)
def get_k(self):
return self.kp, self.ki, self.kd