Negative values??

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…

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?

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. :slight_smile:
I guess this was the problem.

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]

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.