Pages: [1]   Go Down
Author Topic: Negative values??  (Read 749 times)
0 Members and 1 Guest are viewing this topic.
0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

Code:
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...
Logged

Atlanta, GA
Offline Offline
Jr. Member
**
Karma: 0
Posts: 51
Arduino boulders
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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?
« Last Edit: January 22, 2008, 03:38:37 pm by simond » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

It's just
int val = 0;

I'm a bit noob... What am I doing wrong?
« Last Edit: January 22, 2008, 03:49:24 pm by Ultra9k » Logged

0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Brazil
Offline Offline
Sr. Member
****
Karma: 0
Posts: 443
..., to learn, to know, to make, to share, to l...
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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]
« Last Edit: January 22, 2008, 03:56:59 pm by adilson » Logged

PCB Designer

Sacramento, CA, USA
Offline Offline
Newbie
*
Karma: 0
Posts: 30
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

0
Offline Offline
Newbie
*
Karma: 0
Posts: 25
Arduino rocks
View Profile
 Bigger Bigger  Smaller Smaller  Reset Reset

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

Pages: [1]   Go Up
Jump to: