Control Surface  1.1.1
MIDI Control Surface library for Arduino
EMA.hpp
Go to the documentation of this file.
1 /* ✔ */
2 
3 #pragma once
4 
6 AH_DIAGNOSTIC_WERROR() // Enable errors on warnings
7 
8 #include <stdint.h>
9 
41 template <uint8_t K, class uint_t>
42 class EMA {
43  public:
51  uint_t filter(uint_t input) {
52  filtered += input;
53  uint_t output = (filtered + fixedPointAHalf) >> K;
54  filtered -= output;
55  return output;
56  }
57 
65  uint_t operator()(uint_t value) { return filter(value); }
66 
67  static_assert(
68  uint_t(0) < uint_t(-1), // Check that `uint_t` is an unsigned type
69  "Error: the uint_t type should be an unsigned integer, otherwise, "
70  "the division using bit shifts is invalid.");
71 
72  private:
73  uint_t filtered = 0;
74  constexpr static uint_t fixedPointAHalf = 1 << (K - 1);
75 };
76 
77 // -------------------------------------------------------------------------- //
78 
93 class EMA_f {
94  public:
105  EMA_f(float pole) : alpha(1 - pole) {}
106 
114  float filter(float value) {
115  filtered += (value - filtered) * alpha;
116  return filtered;
117  }
118 
126  float operator()(float value) { return filter(value); }
127 
128  private:
129  float alpha;
130  float filtered = 0;
131 };
132 
EMA::filter
uint_t filter(uint_t input)
Filter the input: Given , calculate .
Definition: EMA.hpp:51
EMA::fixedPointAHalf
constexpr static uint_t fixedPointAHalf
Definition: EMA.hpp:74
Warnings.hpp
EMA::filtered
uint_t filtered
Definition: EMA.hpp:73
EMA_f::alpha
float alpha
Definition: EMA.hpp:129
AH_DIAGNOSTIC_POP
#define AH_DIAGNOSTIC_POP()
Definition: Warnings.hpp:17
EMA_f
A class for single-pole infinite impulse response filters or exponential moving average filters.
Definition: EMA.hpp:93
EMA
A class for single-pole infinite impulse response filters or exponential moving average filters.
Definition: EMA.hpp:42
EMA_f::filtered
float filtered
Definition: EMA.hpp:130
EMA_f::EMA_f
EMA_f(float pole)
Create an exponential moving average filter with a pole at the given location.
Definition: EMA.hpp:105
EMA_f::operator()
float operator()(float value)
Filter the input: Given , calculate .
Definition: EMA.hpp:126
AH_DIAGNOSTIC_WERROR
#define AH_DIAGNOSTIC_WERROR()
Definition: Warnings.hpp:16
EMA::operator()
uint_t operator()(uint_t value)
Filter the input: Given , calculate .
Definition: EMA.hpp:65
EMA_f::filter
float filter(float value)
Filter the input: Given , calculate .
Definition: EMA.hpp:114