Control Surface  1.2.0
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:
44  EMA(uint_t initial = 0)
45  : filtered((initial << K) - initial) {}
46 
53  void reset(uint_t value = 0) {
54  filtered = (value << K) - value;
55  }
56 
64  uint_t filter(uint_t input) {
65  filtered += input;
66  uint_t output = (filtered + fixedPointAHalf) >> K;
67  filtered -= output;
68  return output;
69  }
70 
78  uint_t operator()(uint_t value) { return filter(value); }
79 
80  static_assert(
81  uint_t(0) < uint_t(-1), // Check that `uint_t` is an unsigned type
82  "Error: the uint_t type should be an unsigned integer, otherwise, "
83  "the division using bit shifts is invalid.");
84 
85  private:
86  uint_t filtered = 0;
87  constexpr static uint_t fixedPointAHalf = K > 0 ? 1 << (K - 1) : 0;
88 };
89 
90 // -------------------------------------------------------------------------- //
91 
106 class EMA_f {
107  public:
118  EMA_f(float pole) : alpha(1 - pole) {}
119 
127  float filter(float value) {
128  filtered += (value - filtered) * alpha;
129  return filtered;
130  }
131 
139  float operator()(float value) { return filter(value); }
140 
141  private:
142  float alpha;
143  float filtered = 0;
144 };
145 
EMA::filter
uint_t filter(uint_t input)
Filter the input: Given , calculate .
Definition: EMA.hpp:64
EMA::EMA
EMA(uint_t initial=0)
Definition: EMA.hpp:44
EMA::fixedPointAHalf
constexpr static uint_t fixedPointAHalf
Definition: EMA.hpp:87
Warnings.hpp
EMA::reset
void reset(uint_t value=0)
Reset the filter to the given value.
Definition: EMA.hpp:53
EMA::filtered
uint_t filtered
Definition: EMA.hpp:86
EMA_f::alpha
float alpha
Definition: EMA.hpp:142
AH_DIAGNOSTIC_POP
#define AH_DIAGNOSTIC_POP()
Definition: Warnings.hpp:36
EMA_f
A class for single-pole infinite impulse response filters or exponential moving average filters.
Definition: EMA.hpp:106
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:143
EMA_f::EMA_f
EMA_f(float pole)
Create an exponential moving average filter with a pole at the given location.
Definition: EMA.hpp:118
EMA_f::operator()
float operator()(float value)
Filter the input: Given , calculate .
Definition: EMA.hpp:139
AH_DIAGNOSTIC_WERROR
#define AH_DIAGNOSTIC_WERROR()
Definition: Warnings.hpp:35
EMA::operator()
uint_t operator()(uint_t value)
Filter the input: Given , calculate .
Definition: EMA.hpp:78
EMA_f::filter
float filter(float value)
Filter the input: Given , calculate .
Definition: EMA.hpp:127