template <uint16_t Length>

A basic running average low pass filter.

This is a standard moving window / moving average low pass filter, to remove noise from analog input signals. You append raw samples to the filter, and read the filtered output vy value method.

Filter sample values are akways unsigned 16-bit integers, since this is the return type of mbed::AnalogIn

Moving Average Low pass filtering

This digital filter type is quite common, and works well in most cases. You control the filter amount by varying the length og the filter. Longer filters does more aggressive low pass filtering. A filter with the length of 1, does no filtering at all.

The length of a filter object is determined by C++ templating and are fixes for the life-time of the filter.

Appending the first sample

If you create a filter with the length of 100 samples, then if filter will need an initialization period of 100 samples before its output is correctly filtered. To account for this issue you can add the first sample using the clear method, providing it the value of the first value.

This will in most cases help you to no see filter values rise slowly until it stabilizes after 100 samples.


Filter operations are normally O(1), that is constant time. You can append new samples and read filter output in O(1). However, clearing the filter or calculating the variance of the samples is O(n).

To get even faster output calculations use a filter length that is a multi of 2, like 8, 16, 32, 64 etc. This reduce the CPU’s integer division to simple shift operations.


med::AnalogIn adc(J_RING1);
RunningAverageFilter<128> filter(adc.read_u16());

uint16_t lpValue = filter.value();


Public Functions

mono::io::RunningAverageFilter::RunningAverageFilter(uint16_t initialValue)

Construct a filter with an optional initial value.

  • initialValue -

    Provide an initial filter value, for quick stabilization

uint16_t mono::io::RunningAverageFilter::append(uint16_t val)

Add a sample to the filter.

void mono::io::RunningAverageFilter::clear(uint16_t initialValue)

Reset the filter setting all samples to a new value.

Use this method to reset the filter, perhaps after a period of inactivity in the sampling of your signal source.

uint16_t mono::io::RunningAverageFilter::value()

Gets the current low pass filtered value.

uint16_t mono::io::RunningAverageFilter::sum()

Get the sum of all samples in the filter.

uint16_t mono::io::RunningAverageFilter::variance()

Get the variance of the filter samples.

uint16_t mono::io::RunningAverageFilter::operator[](uint16_t indx)

Get a specific sample from the filters array of samples.

uint16_t mono::io::RunningAverageFilter::length()

Get the length of the filter.