Home > Articles, Data Structures & Algorithms, Embedded Systems > How to read smoothly an average value from a jumpy or erratic input sensor.

How to read smoothly an average value from a jumpy or erratic input sensor.

Below, is an Arduino function for reading smoothly an average value from a jumpy or erratic analog input sensor. The function reads repeatedly from an analog input, calculating a running average and returns the value back to the caller.

Here is the function :

// get an average value from a jumpy or erratic input sensor.
const int getSensorAverageValue (const int sensorPin,
                                 const int numberOfSamples,
                                 const long timeGap)
{
  static int currentSample; // current sensor sample.
  static int currentValue;  // current sensor value.

  // current value works as a sum counter.
  currentValue = 0;

  // get sensor samples with delay and calculate the sum.
  for (int i = 0; i < numberOfSamples; i++) {
    // get sensor sample.
    currentSample = analogRead(sensorPin);

    // add sample to the sum counter.
    currentValue += currentSample;

    // delay some time for the next sample.
    delay(timeGap);
  }

  // get the average sensor value (ignore the fraction).
  return (currentValue / numberOfSamples);
}
  1. No comments yet.
  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: