-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDerivativeCalculator.java
More file actions
53 lines (42 loc) · 1.46 KB
/
DerivativeCalculator.java
File metadata and controls
53 lines (42 loc) · 1.46 KB
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
package frc.lib.NinjasLib;
import edu.wpi.first.math.filter.LinearFilter;
import edu.wpi.first.wpilibj.Timer;
public class DerivativeCalculator {
private final LinearFilter lowPassFilter;
private double lastValue;
private double lastTimestamp;
private boolean initialized = false;
private double lastDerivative;
/**
* @param averageWindow The number of samples to average over.
* Higher = smoother but more "laggy". Try 5-10.
*/
public DerivativeCalculator(int averageWindow) {
this.lowPassFilter = LinearFilter.movingAverage(averageWindow);
}
public double calculate(double currentValue) {
double currentTime = Timer.getFPGATimestamp();
if (!initialized) {
lastValue = currentValue;
lastTimestamp = currentTime;
initialized = true;
return 0.0;
}
double dt = currentTime - lastTimestamp;
// 1. Calculate the raw "noisy" derivative
double rawDerivative = (dt > 0) ? (currentValue - lastValue) / dt : 0;
// 2. Pass it through the filter to look at the "range of time"
lastDerivative = lowPassFilter.calculate(rawDerivative);
// 3. Update state
lastValue = currentValue;
lastTimestamp = currentTime;
return lastDerivative;
}
public double get() {
return lastDerivative;
}
public void reset() {
initialized = false;
lowPassFilter.reset();
}
}