template<uint8_t K, class input_t = uint_fast16_t, class state_t = typename std::make_unsigned<input_t>::type>
class EMA< K, input_t, state_t >
Exponential moving average filter.
Fast integer EMA implementation where the weight factor is a power of two.
Difference equation: \( y[n] = \alpha·x[n]+(1-\alpha)·y[n-1] \) where \( \alpha = \left(\frac{1}{2}\right)^{K} \), \( x \) is the input sequence, and \( y \) is the output sequence.
An in-depth explanation of the EMA filter
- Template Parameters
-
K | The amount of bits to shift by. This determines the location of the pole in the EMA transfer function, and therefore the cut-off frequency.
The higher this number, the more filtering takes place.
The pole location is \( 1 - 2^{-K} \). |
input_t | The integer type to use for the input and output of the filter. Can be signed or unsigned. |
state_t | The unsigned integer type to use for the internal state of the filter. A fixed-point representation with \( K \) fractional bits is used, so this type should be at least \( M + K \) bits wide, where \( M \) is the maximum number of bits of the input. |
Some examples of different combinations of template parameters:
- Filtering the result of
analogRead
: analogRead returns an integer between 0 and 1023, which can be represented using 10 bits, so \( M = 10 \). If input_t
and output_t
are both uint16_t
, the maximum shift factor K
is \( 16 - M = 6 \). If state_t
is increased to uint32_t
, the maximum shift factor K
is \( 32 - M = 22 \).
- Filtering a signed integer between -32768 and 32767: this can be represented using a 16-bit signed integer, so
input_t
is int16_t
, and \( M = 16 \). (2¹⁵ = 32768) Let's say the shift factor K
is 1, then the minimum width of state_t
should be \( M + K = 17 \) bits, so uint32_t
would be a sensible choice.
Definition at line 58 of file EMA.hpp.