Go Down

Topic: Negative values?? (Read 833 times) previous topic - next topic

Ultra9k

Code: [Select]
void loop()
{
 val = analogRead(analogPin);    // read the input pin
 for(y=0;y<300;y++) {
   val=val+analogRead(analogPin);
   }
 ;

 Serial.println(val);             // debug value
 
 
delay (500);

}


Why do I get a negative value in this loop? If I write 200 instead of 300 I get positive values. There's no reason for me to get a negative value as analogRead(analogPin) is always positive. My objective is to meke an average of the readings but these negative values are ruining my program...

simond

#1
Jan 22, 2008, 09:37 pm Last Edit: Jan 22, 2008, 09:38 pm by simond Reason: 1
What type is val? If it's a signed 8-bit type you'll see -ve amounts.

Oh, it could be a signed type of any bitlength, and still overflow. What does val's declaration look like?

Ultra9k

#2
Jan 22, 2008, 09:48 pm Last Edit: Jan 22, 2008, 09:49 pm by Ultra9k Reason: 1
It's just
int val = 0;

I'm a bit noob... What am I doing wrong?

Ultra9k

If I change it to
long val=0
it works ok.  :)
I guess this was the problem.

Adilson Akashi

#4
Jan 22, 2008, 09:55 pm Last Edit: Jan 22, 2008, 09:56 pm by adilson Reason: 1
analogRead returns an integer value in the range of 0 to 1023:
http://www.arduino.cc/en/Reference/AnalogRead

But if val is an int type, and if its value exceeds 32,767, "they 'roll over' back to their minimum capacitiy":
http://www.arduino.cc/en/Reference/Int

So you can use long type for val. Its limits is 2,147,483,647. Then yous sum will not exceed limits when using 300.

[edit]I didn't see your last post. Almost at same time...[/edit]
PCB Designer

anaidioschrono

I need to verify it, but I believe that there is an issue with Serial.println printing negative values for unsigned long inputs.

Ultra9k

Yes, the problem was that I need to use a long instead of int. Thank you all.

Go Up