Serial.print impacts variable value?

Hi!
I just got my Arduino Kit and tried the “Love-O-Meter” project. I’m observing a behaviour with the Serial.print()-function I just can’t explain.

The Setup should take values for the temperature, take the average and use this as ambient temperature.

Working Code:

const int sensorPin = A0;
float baselineTemp = 0.0;

void setup(){
  
  Serial.begin(9600);
  for (int pinNumber = 2; pinNumber<5; pinNumber++) {
    pinMode(pinNumber,OUTPUT);
    digitalWrite(pinNumber,LOW);
  }
  
  float baselineIn = 0.0;
  int counter = 0;
  while (millis() < 10000) {
    baselineIn += analogRead(sensorPin);
    counter += 1;
    Serial.println(" "); // THIS IS THE MAGIC LINE: If commented out, the returned value is wrong
  }
  baselineIn = baselineIn/counter; // average input reading
  // convert to degrees (taken from datasheet, tmp36) and set baselineTemp
  baselineTemp = ((baselineIn/1023.0*5.0)-0.5)*100;
  Serial.print(baselineTemp);

}

void loop (){
  // do nothing
}

However, if I comment out the line “Serial.println(” “)”, the temperature computed is completely wrong (about 340 instead of 30)?? I thought that Serial.print just prints the information and shouldn’t have any impact on the outcome? Could anyone please give me a hint to explain this behaviour?

Thanks! =)

Serial.println(" "); // creates a line break

Serial.print(baselineTemp); // does not

Are you sure you aren't just mis-reading the output since without the line break, everything is just going to run together?

  while (millis() < 10000) {
    baselineIn += analogRead(sensorPin);
    counter += 1;
    Serial.println(" "); // THIS IS THE MAGIC LINE: If commented out, the returned value is wrong
  }

Takes a lot longer than:

  while (millis() < 10000) {
    baselineIn += analogRead(sensorPin);
    counter += 1;
//Serial.println(" "); // THIS IS THE MAGIC LINE: If commented out, the returned value is wrong
  }

So, you take a lot more readings. It’s possible that you overflow the variable as a result. Or, counter.

Thanks for the fast answers!

So, you take a lot more readings. It's possible that you overflow the variable as a result. Or, counter.

You are absolutely right! I did not realize the Arduino Uno has 16-bit ints, which already top at about 32000. The limit is reached after about 4000 ms. Using a shorter time or choosing the counter to be a float, everything works as it should. :)

Using a shorter time or choosing the counter to be a float

Or, more reasonably, a long.