-
Notifications
You must be signed in to change notification settings - Fork 11
/
RollingAverage.h
65 lines (52 loc) · 1.16 KB
/
RollingAverage.h
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
#ifndef RollingAverage_h
#define RollingAverage_h
#define MAX_ROLLING_AVERAGE_WINDOW 50
/*
RollingAverage.h
By Shea Ivey
https://github.com/sheaivey/ESP32-AudioInI2S
*/
class RollingAverage {
public:
RollingAverage() {
// Initialize values array
resize(MAX_ROLLING_AVERAGE_WINDOW);
}
void resize(uint16_t size) {
windowSize = size;
index = 0;
count = 0;
sum = 0;
for (int i = 0; i < windowSize; i++) {
values[i] = 0.0;
}
}
float addValue(float value) {
// Subtract the oldest value from the sum
sum -= values[index];
// Add the new value to the array and sum
values[index] = value;
sum += value;
// Move to the next index
index = (index + 1) % windowSize;
// Keep track of the number of values added
if (count < windowSize) {
count++;
}
return getAverage();
}
float getAverage() {
if(count == 0) {
return 1;
}
// Calculate the average
return sum / count;
}
private:
uint16_t windowSize = MAX_ROLLING_AVERAGE_WINDOW;
uint16_t index = 0;
uint16_t count = 0;
float values[MAX_ROLLING_AVERAGE_WINDOW];
float sum = 0.0;
};
#endif