-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathPID.java
118 lines (98 loc) · 2.2 KB
/
PID.java
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
package org.firstinspires.ftc.teamcode;
public class PID
{
public double kP;
public double kI;
public double kD;
public double tau;
public double limMin;
public double limMax;
public double limMinInt;
public double limMaxInt;
public double T;
public double tolerance;
private double integrator;
private double prevError;
private double differentiator;
private double prevMeasurement;
public double setPoint;
public boolean atSetpoint;
private double out;
public PID()
{
integrator = 0.0;
prevError = 0.0;
differentiator = 0.0;
prevMeasurement = 0.0;
atSetpoint = false;
out = 0.0;
}
public double calculate(double measurement)
{
/**
* Error
*/
double error = setPoint - measurement;
/**
* Setpoint check
*/
if (Math.abs(error) <= tolerance)
{
atSetpoint = true;
return 0.0;
}
else
{
atSetpoint = false;
}
/**
* Proportional
*/
double proportional = kP * error;
/**
* Integral
*/
integrator = integrator + 0.5 * kI * T * (error + prevError);
/**
* Anti Wind up
*/
if (integrator > limMaxInt)
{
integrator = limMaxInt;
}
else if (integrator < limMinInt)
{
integrator = limMinInt;
}
/**
* Band limit derivative
*/
differentiator = -(2.0 * kD * (measurement - prevMeasurement)
+ (2.0 * tau - T) * differentiator)
/ (2.0 * tau + T);
/**
* Compute
*/
out = proportional + integrator + differentiator;
/**
* Clamp
*/
if (out > limMax)
{
out = limMax;
}
else if (out < limMin)
{
out = limMin;
}
/**
* Store variables
*/
prevError = error;
prevMeasurement = measurement;
/**
* Return final value
*/
return out;
}
}