utils
utilities in C for microcontrollers
moving_average_filter.h
Go to the documentation of this file.
1 
6 #ifndef MOVING_AVERAGE_FILTER_H
7 #define MOVING_AVERAGE_FILTER_H
8 
9 #include <stddef.h>
10 
14 #define MOVING_AVERAGE_FILTER(name, type, size) \
15 struct maf_##name { \
16  type samples[size]; \
17  size_t write; \
18  type sum; \
19  type average; \
20 }; \
21 static inline void maf_##name##_reset(volatile struct maf_##name *self, type value) { \
22  for (size_t i = 0; i < size; ++i) { \
23  self->samples[i] = value; \
24  } \
25  self->sum = value * size; \
26  self->average = value; \
27 } \
28 static inline void maf_##name##_init(volatile struct maf_##name *self) { \
29  self->write = 0; \
30  maf_##name##_reset(self, 0); \
31 } \
32 static inline type maf_##name##_input(volatile struct maf_##name *self, type input) { \
33  type oldest = self->samples[self->write]; \
34  self->sum -= oldest; \
35  self->sum += input; \
36  self->samples[self->write] = input; \
37  self->write++; \
38  self->write %= size; \
39  self->average = self->sum / size; \
40  return self->average; \
41 } \
42 static inline type maf_##name##_last_output(const volatile struct maf_##name *self) { \
43  return self->average; \
44 } \
45 static inline type maf_##name##_last_input(const volatile struct maf_##name *self) { \
46  size_t index = (self->write - 1) % size; \
47  return self->samples[index]; \
48 }
49 
50 #endif //MOVING_AVERAGE_FILTER_H
51