Smoothing data from a sensor

The simplest is to do a moving average of your data. That is, to keep an array of sensor data readings and average them. Something like this (pseudocode):

  data_X = [0,0,0,0,0];

  function read_X () {
      data_X.delete_first_element();
      data_X.push(get_sensor_data_X());
      return average(data_X);
   }

There is a trade-off when doing this. The larger the array you use, the smoother the result will be but the larger the lag between the result and the actual reading is. For example:

                           /\_/\
                        /\/     \_/\
  Sensor reading:  __/\/            \/\
                                       \/\  _/\___________
                                          \/
                              _
                           __/ \_
                       ___/      \__
  Small array:     ___/             \_/\_       _
                                         \   __/ \________
                                          \_/

                                 ____
                              __/    \__
                           __/           \__
  Large array:     _______/                 \__      __
                                               \_   /  \__
                                                 \_/


(forgive my ASCII-ART but I'm hoping it's good enough for illustration).

If you want fast response but good smoothing anyway then what you’d use is a weighted average of the array. This is basically Digital Signal Processing (with capital DSP) which contrary to its name is more closely related to analog design. Here’s a short wikipedia article about it (with good external links which you should read if you want to go down this path): http://en.wikipedia.org/wiki/Digital_filter

Here’s some code from SO about a low pass filter which may suit your needs: Low pass filter software?. Notice that in the code in that answer he’s using an array of size 4 (or order 4 in signal processing terminology because such filters are called fourth-order filter, it can actually be modeled by a 4th order polynomial equation: ax^4 + bx^3 + cx^2 + dx).

Leave a Comment