View Full Version : [Question(s)] Strange Arduino Glitch "Or bad programing on my part"

01-11-2010, 09:26 PM
I am having a strange problem with my arduino sensor averaging code. Here it is.

int readings[20];
long total = 0;
int average = 0;
int i;

int inputPin = 2;

void setup()

void loop()
for (i=0; i<=20; i++)
readings[i] = analogRead(inputPin);
total += readings[i];
average = total / 20; // calculate the average
total = 0;

Everything works fine until the program leaves the for loop. Until that point the "total" value is accurate however after leaving the for loop "total" changes to a value like 200 that raises and lowers according to the sensors reading. It would appear that after the for loop "total" takes on the value of a single sensor reading instead of 20 sensor readings. Not sure why this is happening or what to google.

01-11-2010, 09:35 PM
I wish I could retract that last post. Fooled around and found the problem. I didn't have enough spaces to store reading because I used 20 when I should have used 21.

01-11-2010, 10:16 PM
What about something like

int getAverageReading()
int total= 0;
int count = 0;

while (count < 20)
total += analogRead(inputPin);

return temp/count;