I have been trying to find a way to read the LM35 as accurately as possible.
I have tried just about every code example I could find on the Internet, nothing seemed to calculate an accurate temperature, so I've combined the best of what I could find and made my own super accurate function.
For a start just about every formula for converting the analog reading to a temperature value divides by 1024, I don't know if this is correct or not but I assume since the ADC returns values between 0 and 1023 that the number should instead be 1023, it seems to yield super accurate numbers anyway, sometimes .01 degree within a DS18B20.
I used example schematic number 7 in the LM35 data sheet, which shows 2 1N914's (I used 1N1418's as this was all I had handy) in series between LM35 ground pin and ground, an 18k resistor between Vout and ground, Arduino analog pin 0 is connected to Vout and analog pin 1 is connected to the ground pin for reading the actual ground voltage that the LM35 see's, this is important as it gives us a reference that is subtracted from the ADC reading on pin 0, this also allows the LM35 to measure negative temperatures, I have taken this to minus 19 so far and it was within .5 of a degree of a DS18B20.
Here's the code, have fun.
Declare:
#define LM35pin 0 // connect LM35 Vout pin to arduino analog pin 0
#define LM35ref 1 // connect 2x 1N1418 diodes between LM35 ground pin and ground
float LM35tempC;
Usage:
LM35tempC = readLM35(LM35pin, true); // true = temp in celcius, false = temp in fahrenheit
Function:
float readLM35(byte LM35Pin, boolean celcius){
int analogVal = 0;
for(int i = 0; i < 10; i++) { // takes 10 samples to make sure we get a good value
analogVal += (analogRead(LM35pin) – analogRead(LM35ref)); // subtract Vout ADC reading from LM35 ground ADC reading
delay(10);
}
float tempC = (5.0 * analogVal * 10) / 1023;
if (celcius == true) {
return tempC; // return temperature in degrees Celcius
}
else {
return (tempC * 9 / 5) + 32; // return temperature in degrees Fahrenheit
}
}
Here's a test run of the above function, I can provide the sketch on request.
LM35 25.86
DS18 25.69
LM35 25.90
DS18 25.75
LM35 26.39
DS18 26.19
LM35 26.39
DS18 26.56
LM35 27.03
DS18 26.81
LM35 27.32
DS18 27.12
LM35 27.37
DS18 27.31
LM35 27.47
DS18 27.50
LM35 27.76
DS18 27.62
LM35 27.86
DS18 27.75
LM35 27.86
DS18 27.69