# Smoothing

The code of the example "Smoothing" given in "Learning" works fine if numReadings remains below 50, otherwise negative values are obtained. Is there a size limit for the storage of an array? Is there a way around?

You can accumulate the readings as you go

then divide them after any number of samples you want.

Here's another way:

``````smoothed = (smoothed+newVal) / 2; //running average
``````

You didn’t answer to my concern.
The example given in Arduino Learning is written like that:

``````const int numReadings = 10;

int index = 0;                  // the index of the current reading
int total = 0;                  // the running total
int average = 0;                // the average

int inputPin = 0;

void setup()
{
// initialize serial communication with computer:
Serial.begin(9600);
// initialize all the readings to 0:
}

void loop() {
// advance to the next position in the array:
index = index + 1;

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

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

so it includes the equivalent of GrumpyMike’s
it is:
The problem is not there! But here:
Why for higher numbers of accumulated data the code doesn’t work anymore? (It gives NEGATIVE average!!!)

What AlphaBeta proposes is fine for two values. But what about an average on 50 data?

The problem with the sketch is probably that it uses an "int" (16 bit) value for the array total variable "total".

Try changing it for a "long".

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

Explanation: Assume your analogue readings are all roughly at the three-quarters range for an analogue input, say 768. If you accumulate fifty of these, your total would be 38 400. However, a signed 16 bit variable can only represent the range -32 768 ... +32767, so the total will "wrap around" and start giving negative values. Using a "long" (32 bit signed) gets around this problem, and you could sum far more samples than the Arduino has capacity for (just over two million 10-bit samples).

What AlphaBeta proposes is fine for two values. But what about an average on 50 data?

It will provide you with a dynamic average that grows and shrinks in sync with your dataset.

A regular average will disregard the nuances of the dataset, and might be better if you want to smooth noisy signals, [because the neuances and differences is what you try to smooth] but if your signal is relatively stable, a running average might cause your application to perform more naturally.

thanks a lot for you all! I tried also with "float" and it works.