-
Notifications
You must be signed in to change notification settings - Fork 0
/
PIController.java
executable file
·100 lines (93 loc) · 2.06 KB
/
PIController.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
package org.usfirst.frc.team3238.robot;
/**
* This is a generic proportional integral controller.
*
* @author Nick Papadakis
*/
public class PIController
{
double m_cummulativeError = 0;
double m_oldTime = 0;
double m_pConstant;
double m_iConstant;
double m_throttle;
PIController(double pConstant, double iConstant)
{
m_pConstant = pConstant;
m_iConstant = iConstant;
m_throttle = 1.0;
}
/**
* Takes the current setpoint and sensorValue and calculates the necessary
* response using the PI loop
*
* @param setpoint
* The desired sensorValue
* @param sensorValue
* The current value of the sensor
* @return m_returnPower The motor power calculated by the PI loop to get
* the sensorValue closer to the setpoint
*/
double getMotorValue(double setpoint, double sensorValue)
{
double error = setpoint - sensorValue;
m_cummulativeError += error;
double time = System.currentTimeMillis();
// If this is the first loop, set timeDifference to 0
double timeDifference;
if (m_oldTime == 0)
{
timeDifference = 0;
}
else
{
timeDifference = time - m_oldTime;
}
double returnPower;
if (error != 0)
{
returnPower = error * m_pConstant + m_cummulativeError * m_iConstant * timeDifference;
}
else
{
returnPower = 0;
}
// Set up the "old" values for the next loop
m_oldTime = time;
return limitOutput(returnPower) * m_throttle;
}
/**
* Resets the cummulativeError and oldTime variables
*/
void reinit()
{
m_cummulativeError = 0;
m_oldTime = 0;
}
void inputConstants(double pConstant, double iConstant)
{
m_pConstant = pConstant;
m_iConstant = iConstant;
}
void setThrottle(double throttle)
{
m_throttle = throttle;
}
double limitOutput(double motorPower)
{
double returnPower;
if (motorPower > 1.0)
{
returnPower = 1.0;
}
else if (motorPower < -1.0)
{
returnPower = -1.0;
}
else
{
returnPower = motorPower;
}
return returnPower;
}
}