Simple Moving Average

A Simple Moving Average is a type of signal filter or algorithm designed to ‘smooth out’ fluctuations in a data stream. This diagram explains it visually:

A visualised example of a averaging filter applied to noisy data. Jagged blue line represents raw data. Smooth, superimposed black curve represents averaged filter. Image: [http://www.biomecardio.com/matlab/sffilt.html](https://web.archive.org/web/20151207022337/http://www.biomecardio.com/matlab/sffilt.html)

A visualised example of a averaging filter applied to noisy data. Jagged blue line represents raw data. Smooth, superimposed black curve represents averaged filter. Image: http://www.biomecardio.com/matlab/sffilt.html

Such filters are integral to working with sensors, especially sensors that are naturally prone to high levels of fluctuation, i.e. noise. You can often see this when you trace the output of a noisy analogue reading to the Serial Port.

Examples of ‘noisy’ analogue sensors:

  • Audio microphones
  • Distance/proximity sensors
  • LDRs (light-dependent resistors)
  • FSRs (force-sensitive resistors)

To ‘massage’ these raw sensor values to get a smoother response over time, we can implement signal filters in code. For the purpose of this studio, let’s look at the basic but highly effective Simple Moving Average (SMA) filter.

Effectively, this filter performs the following steps:

  1. Store the last n number of readings of the sensor into an array (i.e. a list of numbers stored in memory)
  2. Find the average of these n readings – and use this averaged reading
  3. Continue to maintain the last n number of readings constantly (hence moving average)
  4. Repeat from step 2

It will therefore make sense that the size of the array, i.e. n, will impact the rate of change of the averaged reading. A higher n value will result in slower, less-responsive sensor reading but one that is extremely stable. Depending on your sensor and application scenario, you will then experiment with raising/lowering this n value to strike the right balance between responsiveness and stability.

Filters in Hardware?

You can also implement filters in hardware (look for RC or LC circuits as an example), instead of writing code. The benefit of hardware filters is zero coding, but a deeper understanding of electrical characteristics of inductors, resistors and capacitors are required.

Code

There are two suggested ways to implement an SMA filter in your coding project. The first method uses the RunningAverage code library written by Rob Tillaart. This is easily installed via the Arduino Library Manager, and can be quickly ported to other similar platforms. The second method does not rely on a 3rd-party library, which consequently bulks up the code that you have to write.

The non-library version is more to illustrate how a SMA filter works; RunningAverage abstracts all of this complexity away so we can focus on other things.

  • Libraries Used

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    
    /*
        Please note that the code provided here is licensed under the MIT license.
    
        The MIT License (MIT)
        Copyright © 2024 Chuan Khoo
    
        Permission is hereby granted, free of charge, to any person obtaining
        a copy of this software and associated documentation files (the
        "Software"), to deal in the Software without restriction, including
        without limitation the rights to use, copy, modify, merge, publish,
        distribute, sublicense, and/or sell copies of the Software, and to
        permit persons to whom the Software is furnished to do so, subject to
        the following conditions:
    
        The above copyright notice and this permission notice shall be included
        in all copies or substantial portions of the Software.
    
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
        OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
        THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
        OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
        ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
        OTHER DEALINGS IN THE SOFTWARE.
    */
    
    // This SMA example uses floating point math, as the RunningAverage filter supports floats.
    
    #include "RunningAverage.h"
    #define FILTERSIZE  10    // adjust this to set the aggressiveness of your filter
    #define INITIAL_VAL 0     // filter should have an initial value   
    
    RunningAverage myRA(FILTERSIZE);  // initialise the RunningAverage library object
    float smaAvg = 0;                 // variable to store the average
    int rawReading;                   // variable to store raw readings
    
    void setup() {
        Serial.begin(115200);
        myRA.clear();         // initialise the SMA filter
        myRA.fillValue(INITIAL_VAL, FILTERSIZE);    // fill the filter with INITIAL_VAL
    }
    
    void loop() {
        // for simplicity, we are reading a fictitious analog sensor connected to A0
        // if you are using I2C sensors, edit the code accordingly
    
        rawReading = analogRead(A0);    
        // an example of using constrain to 'crop' outlying values not reported by sensor
        rawReading = constrain(rawReading, 100, 800);
        runRA();   // run the runRA() function (below)
    }
    
    // a custom function that we call from loop() – keeps the main loop() uncluttered!
    void runRA() {
        myRA.addValue(rawReading);
        smaAvg = myRA.getAverage();
        Serial.print("avg: ");
        Serial.println(smaAvg, 3);      // print up to 3 decimal places
    }
    
  • Libraries Used

    • None

    Code

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    
    /*
        Please note that the code provided here is licensed under the MIT license.
    
        The MIT License (MIT)
        Copyright © 2017 Chuan Khoo
    
        Permission is hereby granted, free of charge, to any person obtaining
        a copy of this software and associated documentation files (the
        "Software"), to deal in the Software without restriction, including
        without limitation the rights to use, copy, modify, merge, publish,
        distribute, sublicense, and/or sell copies of the Software, and to
        permit persons to whom the Software is furnished to do so, subject to
        the following conditions:
    
        The above copyright notice and this permission notice shall be included
        in all copies or substantial portions of the Software.
    
        THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS
        OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
        FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
        THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR
        OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
        ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
        OTHER DEALINGS IN THE SOFTWARE.
    */
    
    // This SMA example uses integer math, which means that all averaged values are integers.
    // if you need the precision of floating point (i.e. decimal points), change the int datatypes to float (smaBuf, smaTotal, smaAvg, rawReading).
    
    #define FILTERSIZE  10    // adjust this to set the aggressiveness of your filter
    #define INITIAL_VAL 0     // filter should have an initial value   
    
    int smaBuf[FILTERSIZE];   // this is the array 'buffer' in which we are storing the 'historical' values of a sensor reading
    int smaIdx = 0;           // an index counter to iterate across readings in the buffer
    int smaTotal = INITIAL_VAL * FILTERSIZE;        // track the running total
    int smaAvg = 0;                                 // variable to store the average
    int rawReading;                                 // variable to store raw readings
    
    void setup() {
        Serial.begin(115200);
        // pre-populate the filter buffer with INITIAL_VAL
        for(int i=0; i<FILTERSIZE; i++) {
            smaBuf[i] = INITIAL_VAL;
        }
    }
    
    void loop() {
        // for simplicity, we are reading a fictitious analog sensor connected to A0
        // if you are using I2C sensors, edit the code accordingly
        rawReading = analogRead(A0);    
    
        // an example of using constrain to crop outlying values not reported by sensor
        rawReading = constrain(rawReading, 100, 800);
    
        runSMA();   // run the runSMA() function (below)
    }
    
    // a custom function that we call from loop() – keeps the main loop() uncluttered!
    void runSMA() {
        smaTotal -= smaBuf[smaIdx];
        smaBuf[smaIdx] = rawReading;
        smaTotal += smaBuf[smaIdx];
        smaIdx++;
        if (smaIdx >= FILTERSIZE)
            smaIdx=0;
        smaAvg = smaTotal / FILTERSIZE;
    
        Serial.printlnf("avg: %i", smaAvg);
    }
    

This page was last updated: 23 Sep 2024