LM35DZ temp readings when powered from battery/USB

I have a couple of LM35DZ temperature sensors around, and while they are supposedly precise and calibration-free, I get some strange values from them.

More specifically, if I'm powering the Arduino from the USB port, the readings are always 1ºC higher than those I get when powering the Arduino from a 9V rechargeable battery. :-?

As I'm not so well versed in electronics, I'm unsure of where this difference may come from or how to work around it.

The code I'm using is:

static const char sensorPin = 0;
static const char ledPin = 13;
static const char samples = 10;


void setup() {
  Serial.begin(9600);
  
  pinMode(ledPin, OUTPUT);
}


void loop() {
  digitalWrite(ledPin, HIGH);

  float temp = 0;
  
  /* Read the temperature a few times and average the results... */
  for (int i = 0; i < samples; i++) {
    temp += (5.0 * analogRead(sensorPin) * 100.0) / 1024.0;
    delay(10);
  }
  temp /= samples;

  Serial.println(temp);

  digitalWrite(ledPin, LOW);  
  delay(500);
}

I'm unsure of where this difference may come from or how to work around it.

It comes from the fact that the USB and the regulator produce slightly different voltages and it is this voltage that is used for the reference voltage for the A/D. How much do you want to get them to match, you need an externally stabilised reference.

check it out here on hardikpandya.com. i have done the same project as you and you might find something worthy.