-
Notifications
You must be signed in to change notification settings - Fork 0
/
pid.py
123 lines (99 loc) · 2.93 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
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
# -*- coding: utf-8 -*-
"""
Based on Arduino PID Library (Version 1.0.1) by Brett Beauregard <[email protected]> brettbeauregard.com
"""
from __future__ import division
import sys
import time
#import ms5837
#import Adafruit_PCA9685
#kp = 130 , ki = 80 , kp = 0.1
kp = 130.0
ki = 80.0
kd = 0.1
direct = True
sample_time = 0.01 # seconds
output_value = 0.0
last_input = 0.0
out_max = 400
out_min = 230
zero_offset = 305
freshwaterDepth = 0.0
setpoint = 0.0
i_term = 0.0
windup_guard = 20.0
sensor_offset = 0.0
#sensor = ms5837.MS5837_30BA()
# We must initialize the sensor before reading it
#if not sensor.init():
# exit(1)
#pwm = Adafruit_PCA9685.PCA9685()
#pwm.set_pwm_freq(50)
last_time = time.time() - sample_time
#sensor.setFluidDensity(1000) # kg/m^3
def compute(kp,ki,kd,direct,setpoint,freshwaterDepth,
sample_time,last_time,windup_guard,i_term,
output_value,last_input,out_min,out_max):
now = time.time()
time_change = now - last_time
input_value = freshwaterDepth
error = setpoint - input_value
i_term += ki * error * sample_time
if i_term > windup_guard:
i_term = out_max
elif i_term < -windup_guard:
i_term = out_min
delta_input = input_value - last_input
output = (kp * error) + i_term + (kd * (delta_input / sample_time))
print(output)
output += zero_offset
if output > out_max:
output = out_max
elif output < out_min:
output = out_min
output_value = output
last_input = input_value
last_time = now
return output_value
if __name__ == '__main__':
#if sensor.read():
# print("yalla")
#print(sensor.depth())
setpoint = input("enter height : ")
#freshwaterDepth = input("enter depth : ")
setpoint = float(setpoint)
#freshwaterDepth = float(freshwaterDepth)
#pwm.set_pwm(8, 0, 305)
#pwm.set_pwm(10, 0, 305)
time.sleep(1)
#if sensor.read():
# sensor_offset=sensor.depth()
try:
while True:
#if not sensor.read():
# print("no")
#freshwaterDepth = sensor.depth() # default is freshwater
#freshwaterDepth = float(freshwaterDepth)-sensor_offset
#print("Depth: %.3f m (freshwater)" % (freshwaterDepth))
val = compute(kp,ki,kd,direct,setpoint,freshwaterDepth,
sample_time,last_time,windup_guard,i_term,
output_value,last_input,out_min,out_max)
print("pwm: " + str(val))
if val:
val = int(val)
'''
pwm.set_pwm(8, 0, val)
pwm.set_pwm(10, 0, val)
'''
last_time = time.time()
else :
print("\n")
time.sleep(0.01)
except KeyboardInterrupt:
time.sleep(0.1)
print("no")
'''
pwm.set_pwm(8, 0, 305)
pwm.set_pwm(10, 0, 305)
'''
sys.exit()