Go Down

Topic: Negative values?? (Read 1 time) previous topic - next topic


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

 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...


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?


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?


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

Adilson Akashi

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:

But if val is an int type, and if its value exceeds 32,767, "they 'roll over' back to their minimum capacitiy":

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


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


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

Go Up

Please enter a valid email to subscribe

Confirm your email address

We need to confirm your email address.
To complete the subscription, please click the link in the email we just sent you.

Thank you for subscribing!

via Egeo 16
Torino, 10131