Ron
Ron

Reputation: 133

Arduino loop update of a variable is incorrect

I've got the following code snippet in the setup() function:

...
unsigned int a0val;
unsigned int a0total = 0;
...
for (i = 0; i < 1000; i++) {
    a0val = analogRead(A0);
    Serial.println(a0val);
    a0total += a0val;
}
Serial.println(a0total);
...

This is done to baseline the analog value at startup to account for different types of sensors being used. One type may read 0 and another may read some non-zero value. The point is to have a starting point reference by averaging 1000 readings at startup time. 1000 is obviously overkill, I'll cut back later.

Now, with 1000 readings somewhere between 128 and 130, I expect a0total to be around 129,000. However, the total consistently comes out less than half that number, like 63,722 in one example. It's not even half, it's less than that.

Another example: I add up the first 500 readings when they are all around 350-352, and the total came out to 43614. It looks like wrap-around, but I'm using unsigned int for both values so that can't be happening.

So to me it almost looks like "a0total += a0val" is not updating every loop, but that doesn't make sense either.

What am I missing?

Thanks, Ron

Upvotes: 1

Views: 97

Answers (1)

KIIV
KIIV

Reputation: 3739

You are missing size of unsigned int on this platform. It is 16bits and therefore the maximum value is 65535.

Upvotes: 2

Related Questions