Sensor jitter problems? Let's fight back

I wrote a tiny function in Arduino-C for my sensor-jitter problems. You can smooth out your sensor readings with this little function. You can input the smoothness and then get back the smoothed sensor value.

If somebody needs it - here it is:


// Jan Przybilla, Rosk, Farbtonstudio.de
// SSR - Smooth Sensor Readings
// Fight the (((Jitter)))!


#define SMOOTH 10                  // Sensor Smoothness (5 - 50)
int readings[SMOOTH];              // Smoothcounter Variable
int index = 0;                               // Smoothindex Var
int total = 0;                                 // Runcounter
int average = 0;                           // Var average
int readMe = 0;                            // Read this Pin
int p_val;                                      // Smoothed Variable

// Average sensor value
void sensorval(){
  total -= readings[index];               // substract the last value
  readings[index] = analogRead(readMe);   // read the sensor
  total += readings[index];             // add the value
  index = (index + 1);                    // goto next index

  if (index >= SMOOTH)               // if we are at the end of the array
    index = 0;                                 // ...go to the beginning

  average = total / SMOOTH;       // average from all readings
  // ...giveback
  p_val = average;
}

void setup()
{
  // SERIAL OUTPUT
  Serial.begin(9600);             // Serial Output start
  for (int i = 0; i < SMOOTH; i++)
    readings[i] = 0;              // reset all Smoothreadings to 0
}

void loop()
{       
  // Sensor Jitter-average loop
    sensorval();
    Serial.println(p_val);               // Show smoothed value  
}

Nice tip. I’m collecting

Nice tip. I’m collecting this one.

I suggest you post it as a Tip/Walkthrough instead of a blog.