-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathfir.h
More file actions
54 lines (47 loc) · 1.49 KB
/
Copy pathfir.h
File metadata and controls
54 lines (47 loc) · 1.49 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
54
#pragma once
#include <stddef.h>
/// @brief FIR filter class
/// @tparam N_TAPS Number of filter taps to allocate
template <size_t N_TAPS>
class FirFilter {
public:
/// @brief Create a FIR filter
/// @param taps List of tap coefficients. Must have exactly N_TAPS coefficients as defined in the template.
FirFilter(const float taps[N_TAPS]) : taps(taps), samples(), last_index(0)
{
for (int i = 0; i < N_TAPS; i++) {
samples[i] = 0;
}
}
/// @brief Add a sample to the filter
/// @param sample Value to filter
void add(float sample) {
samples[last_index++] = sample;
if (last_index == N_TAPS) {
last_index = 0;
ready = true;
}
}
/// @brief Get the current filtered value
/// @return Filtered value
float get() const {
float acc = 0;
int index = last_index;
for (int i = 0; i < N_TAPS; ++i) {
index = index != 0 ? index-1 : N_TAPS-1;
acc += samples[index] * taps[i];
};
return acc;
}
/// @brief Whether the filter is ready to return a sample
bool isReady() const {
return ready;
}
private:
const float* taps;
std::array<float, N_TAPS> samples;
unsigned int last_index;
bool ready;
};
#define DEFINE_FIR_FILTER(taps) FirFilter<(sizeof(taps)/sizeof(taps[0]))>
#define MAKE_FIR_FILTER(taps) (FirFilter<(sizeof(taps)/sizeof(taps[0]))> { taps })