Open FFBoard
Open source force feedback firmware
FastAvg.h
Go to the documentation of this file.
1/*
2 * FastAvg.h
3 *
4 * Created on: Sept 28, 2021
5 * Author: Vincent Manoukian + Yannick Richter
6 */
7
8#ifndef FAST_AVERAGE_H_
9#define FAST_AVERAGE_H_
10
11#include <FFBoardMain.h>
12
13template <class T,std::size_t LEN>
14class FastAvg {
15
16public:
19
20 __attribute__((optimize("-Ofast")))
21 void addValue(T value) {
22
23 // Add the new value
24 samples[currentIndex] = value;
25 sumOfSamples += value;
26
27 // remove the previous value
28 int indexRemove = (currentIndex + 1) % (LEN+1);
29 sumOfSamples -= samples[indexRemove];
30
31 // prepare the next add
32 currentIndex = indexRemove;
33 }
34
36 return sumOfSamples / LEN;
37 }
38
39 T process(float value) {
40 addValue(value);
41 return sumOfSamples / LEN;
42 }
43
44 void clear() {
45 memset(samples,0,LEN*sizeof(T));
46 sumOfSamples = 0;
47 }
48
49private:
50 T samples[LEN+1] = {static_cast<T>(0)};
51 int currentIndex = 0;
53
54};
55
62template <class T>
64public:
65 FastMovingAverage(int32_t len = 0) : fixedLen(len > 0 ? len : INT32_MAX), count(0){};
67
68 void clear(){
69 curAvg = 0;
70 count=0;
71 }
76 T t = curAvg;
77 clear();
78 return t;
79 }
80
85 return curAvg;
86 }
90 T addValue(T v){
91 if(count < fixedLen)
92 count++;
93 curAvg += (v - curAvg)/count;
94 return curAvg;
95 }
96private:
97 T curAvg = 0;
98 const int32_t fixedLen;
99 int32_t count = 0;
100};
101
102#endif
T sumOfSamples
Definition: FastAvg.h:52
T getAverage()
Definition: FastAvg.h:35
T samples[LEN+1]
Definition: FastAvg.h:50
void clear()
Definition: FastAvg.h:44
__attribute__((optimize("-Ofast"))) void addValue(T value)
Definition: FastAvg.h:20
int currentIndex
Definition: FastAvg.h:51
~FastAvg()
Definition: FastAvg.h:18
T process(float value)
Definition: FastAvg.h:39
FastAvg()
Definition: FastAvg.h:17
void clear()
Definition: FastAvg.h:68
FastMovingAverage(int32_t len=0)
Definition: FastAvg.h:65
const int32_t fixedLen
Definition: FastAvg.h:98
int32_t count
Definition: FastAvg.h:99
T addValue(T v)
Definition: FastAvg.h:90