Arduino Tips Number 2: Moving Averages

Sometimes when you collect data it can be quite noisy and you need to smooth it out. A moving average is perfect for this. There is a good library that makes this easy called microsmooth. If you have the latest version of the Arduino IDE installed it is easy enough to install this. Select the Sketch/include library/manage libraries option form the menu and search for microsmooth.  I've written a small programme to below to demonstrate it's use. This programme will read a value from a light sensor connected to analogue pin A0 once every half a second and write both the unsmoothed and the smoothed value to the Serial port.

The code works as follows:

  • before the setup function we import the library and then setup a pointer to accept the smoothed value and an integer to hold the value of the analogue pin to be read (this just aids in readability of the code later on).
  • in the setup function we initialise the pointer using an function from the microsmooth library and setup the serial port.
  • in the main loop we read the value of the light sensor (or any other sensor) pass this value in to the microsmooth sma function, which is a simple moving average, and print both the unsmoothed and the smoothed values to the serial port.

There are other types of smoothing available in the library

Comments