Wrong data output on first Serial Print

I am using a ATmega328 with optiboot bootloader with a CP2102 TTL-USB converter, and I am reading the ADC value from a LM35 temperature sensor, with a very simple code of just converting the value to the actual voltage.

The problem is whenever I am opening the serial monitor the first data it prints out is almost double of the actual value, this is happening whenever I am reopening the serial monitor even without re-uploading the code, or resetting/re-powering the board.

This is interfering with my actual project, which sends the data through a wifi-module(ESP8266), so there might be no problem with the TTL-USB converter.

What is the problem here?

Code:

int tempSensorPin = A0;

void setup() {
  Serial.begin(9600);
}

void loop() {
  int sensorValue = analogRead(tempSensorPin);
  float tempValue = sensorValue*100*(4.5/1024.0);
  Serial.print("Temp = ");
  Serial.print(tempValue);
  Serial.print("\tSensorValue = ");
  Serial.println(sensorValue);
  delay(1000);
}

Hi Jimut

Does it help if you change this ...

  int sensorValue = analogRead(tempSensorPin);

... to this?

  int sensorValue = analogRead(tempSensorPin);
  sensorValue = analogRead(tempSensorPin);

Regards

Ray

sensorValue*100

For any value of sensorValue over 327, that multiplication will overflow.

this is happening whenever I am reopening the serial monitor even without re-uploading the code, or resetting/re-powering the board.

You know that opening the Serial Monitor resets the Arduino, right?

Does it help if you change this ...

No, Ray, the problem persists with that change. :frowning:

You know that opening the Serial Monitor resets the Arduino, right?

No, I didn't knew that. But why is it printing out the wrong value first time even when I call analogRead 2 times before printing it out?

For any value of sensorValue over 327, that multiplication will overflow.

sensorValue itself is coming wrong, first value gives 98, where are all the other gives 28.

Ok, I solved it.

Calling the analogRead and making a delay for the first time solves the problem. I think there is a massive voltage ripple during the time of resetting the MCU which is causing the problem.

By the way, I am also having a voltage sag, which is causing the ADC to measure 200mV less than the actual voltage, due to the power hungry ESP8266 sitting beside it. Maybe using a bigger PSU will solve that.

The final code comes to:

int tempSensorPin = A0;

void setup() {
Serial.begin(9600);
analogRead(tempSensorPin);
delay(100);
}

void loop() {
int sensorValue = analogRead(tempSensorPin);
float tempValue = sensorValue100(4.5/1024.0);
tempValue += 20;
Serial.flush();
Serial.print("Temp = ");
Serial.print(tempValue);
Serial.print("\tSensorValue = ");
Serial.println(sensorValue);
delay(1000);
}