Running average of 16bit ADS1115

I connected turbidity sensor TSD-10 to Arduino-Uno via 16bit ADC ADS1115. The output sensor data is slightly unstable, hence I wanted to smoothen the data with the help of "Running average". I am not able to figure out why the running average doesn't seem to work. the ADS1115 is connected to Arduino-Uno via SDA and SLC. Below is the code. I will be thankful for help.

#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads1115(0x48);
const int numReadings = 10;
int readings;
int readIndex = 0;
int total = 0;
int average = 0;
int inputPin = SDA;

void setup(void)
{
Serial.begin(9600);
ads.setGain(GAIN_TWOTHIRDS);
ads1115.begin();
for (int thisReading = 0; thisReading < numReadings; thisReading++) {
readings = 0;
}
}

void loop(void)
{
int16_t adc0;
adc0 = ads1115.readADC_SingleEnded(0);
total = total - readings;
readings = analogRead(inputPin);
total = total + readings;
readIndex = readIndex + 1;
if (readIndex >= numReadings) {
readIndex = 0;
}

average = total / numReadings;
Serial.print("AIN0: "); Serial.println(adc0);
Serial.print("Average: "); Serial.println(average);
Serial.println(" ");
delay(1000);
}

To do a running average, you need to keep an array of all your values so you know what to remove and what to add along with the total.

Also, since your readings are 16 bits, your total needs to by of type 'long int' or else you run the risk of overflow.

#include <Wire.h>
#include <Adafruit_ADS1015.h>
Adafruit_ADS1115 ads1115(0x48);
const int numReadings = 10;
int readings[numReadings];

//int readings;
int readIndex = 0;
long int total = 0;
int average = 0;

void setup(void)
{
  Serial.begin(9600);
  ads.setGain(GAIN_TWOTHIRDS);
  ads1115.begin();
  for (int thisReading = 0; thisReading < numReadings; thisReading++) {
    readings[thisReading] = 0;
  }
}

void loop(void)
{
  int16_t adc0;
  adc0 = ads1115.readADC_SingleEnded(0);
//  readings = analogRead(inputPin);
  total = total - readings[readIndex];
  readings[readIndex] = adc0;
  total = total + readings[readIndex];
  readIndex = readIndex + 1;
  if (readIndex >= numReadings) {
    readIndex = 0;
  }

  average = total / numReadings;
  Serial.print("AIN0: "); Serial.println(adc0);
  Serial.print("Average: "); Serial.println(average);
  Serial.println(" ");
  delay(1000);
}

My guess is that 10 of your 16-bit ADC values won't fit into a 16-bit value. Try making 'total' a long instead of int.

Not that it's part of your issue, but why set readings to 0 ten times? It's already set to 0 by "int readings;". It's not hurting anything. Just seems odd.

for (int thisReading = 0; thisReading < numReadings; thisReading++) {       
   readings = 0;                                               
  }

use floats? Or more if you got 'em.

-jim lee