smoothing analog input with watch dog timer

I am trying to smooth an analog input while also using the watch dog timer in a sketch. The problem I believe I am running into is my smoothing function only runs once and does not build an index of values to average. I have tried disabling the wdt before running the smoothing loop. Below is the smoothing example I am using. Any help would be greatly appreciated. Thanks

const int numReadings = 10;

int readings[numReadings]; // the readings from the analog input
int index = 0; // the index of the current reading
int total = 0; // the running total
int average = 0; // the average

int inputPin = A0;

void setup()
{
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
for (int thisReading = 0; thisReading < numReadings; thisReading++)
readings[thisReading] = 0;
}

void loop() {
// subtract the last reading:
total= total - readings[index];
// read from the sensor:
readings[index] = analogRead(inputPin);
// add the reading to the total:
total= total + readings[index];
// advance to the next position in the array:
index = index + 1;

// if we're at the end of the array...
if (index >= numReadings)
// ...wrap around to the beginning:
index = 0;

// calculate the average:
average = total / numReadings;
// send it to the computer (as ASCII digits)
Serial.println(average, DEC);
}

I don't see any reference to the watch dog timer, or indeed any timer, in your sketch.

I assume the WDT is configured to generate an interrupt? I've used a similar moving average approach for analog sensors. If the code posted is in a function, then the variables readings, index, total and average probably need to be static so they will retain their values between calls to the smoothing function.

What has the WDT got to do with that code?


Rob

CarlaCarla:
void loop() {
// subtract the last reading:
total= total - readings[index];

Isn't this always going to remove the most recent old reading from the total? Instead, I think you need to change the code so that it removes the oldest, i.e. least recent, reading.

While I've used your averaging approach also, nowadays I normally use a basic RC-type filter for smoothing analog readings:

x = ( some value between 0 and 1, higher values give more smoothing effect )
newaverage = x * oldaverage + ( 1 - x ) * reading;
oldaverage = newaverage;

Jim