# LM35DZ - temperature sensor. Big differences while reading it

**URL:** <https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872>\
**Category:** General Electronics\
**Created:** [February 19, 2011, 9:15am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872 "2011-02-19T09:15:40Z")\
**Posts on this page:** 20\
**Page:** 1

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 9:15am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/1 "2011-02-19T09:15:40Z")

</div>

Good morning

I'm using a LM35DZ - temperature sensor

> **[LM35DZ Datasheet](https://www.futurlec.com/Linear/LM35DZ.shtml)**
>
> LM35DZ Datasheet, LM35DZ National Semiconductor Precision Celcius Temperature Sensor Datasheet , buy LM35DZ Temperature Sensor

I'm using the following code from [Temperature Sensor + Arduino - Daniel Andrade](http://www.danielandrade.net/2008/07/05/temperature-sensor-arduino/)

Here is the code:

> int pin = 1; // analog pin  
> int tempc = 0,tempf=0; // temperature variables  
> int samples[8]; // variables to make a better precision  
> int maxi = -100,mini = 100; // to start max/min temperature  
> int i;
> 
> void setup()  
> {  
> Serial.begin(9600); // start serial communication  
> }
> 
> void loop()  
> {
> 
> for(i=0;i\<=7;i++){ // gets 8 samples of temperature
> 
> samples _= ( 5.0 \* analogRead(pin) \* 100.0) / 1024.0;_  
> \_ tempc = tempc + samples\*;_\_  
> \__ delay(1000);_\_  
> \__}_\_  
> tempc = tempc/8.0; // better precision  
> Serial.print(tempc,DEC);  
> Serial.println("º");  
> tempc = 0;  
> delay(1000); // delay before loop  
> \__}_\_  
> \__[/quote]\*\_  
> _But it happens that I have great differences between reads..._  
> _17º_  
> _16º_  
> _16º_  
> _17º_  
> _15º_  
> _19º_  
> _17º_  
> _19º_  
> _16º_  
> _21º_  
> _19º_  
> _16º_  
> _16º_  
> _ **13º** _  
> _16º_  
> _20º_  
> _ **21º** _  
> _16º_  
> _20º_  
> _18º_  
> _18º_  
> _18º_  
> _What can I do?_  
> _The cable that I'm using, is a 2 meters shielded cable with 3 wires, the same cable used on encoders._  
> _Please let me know_  
> _Thanks on advance_  
> _Pedro Ferrer_

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 10:13am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/2 "2011-02-19T10:13:26Z")

</div>

You must be the lucky one who actually received something from futurlec. 😉

I would start with changing the tempc variable to type float. As it is now you accumulate innacuracy through each analog read iteration due to integer rounding.

To further improve analog sampling, it is typically always better to increase number of samples averaged. That is if your sketch has nothing else to do, you may as well keep sampling continuesly until next output is needed. The trick to achieve this would be to model your skecth after the blink without delay example, maintain a sample counter and then eliminate all calls to delay. When your time interval is reached you calculate the average, output the result and reset the sample counter and accumulator.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 5:39pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/3 "2011-02-19T17:39:38Z")

</div>

Hello BenF

> You must be the lucky one who actually received something from futurlec.

No... actually I've bought on Portugal...

I've changed the var to float. You're right.

But the problem remains...

22.3750000000Âº  
14.8750000000Âº  
18.7500000000Âº  
16.7500000000Âº  
23.2500000000Âº  
19.8750000000Âº  
21.6250000000Âº  
20.3750000000Âº  
21.6250000000Âº  
16.3750000000Âº  
19.7500000000Âº  
20.2500000000Âº  
18.7500000000Âº  
16.7500000000Âº  
18.3750000000Âº

What can I do? Put a pull-down resistor or else?

Please let me know  
Thanks on advance  
Best regards  
Pedro Ferrer

---

<div class="post-metadata">

**Author:** ![cmiyc](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/cmiyc/32/1204108_2.png) [@cmiyc](https://forum.arduino.cc/u/cmiyc)\
**Post date:** [February 19, 2011, 8:04pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/4 "2011-02-19T20:04:30Z")

</div>

> The cable that I'm using, is a 2 meters shielded cable with 3 wires, the same cable used on encoders.

If you use the same sensor with short connections do you see the same behavior?

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 19, 2011, 9:49pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/5 "2011-02-19T21:49:52Z")

</div>

Instead of averaging the temperature you may use the median of 7 readings. The median is the middle value of a sorted array of readings.

Suppose you have 7 readings and 6 are 20C and one is 0C (misread).  
Average = 6x20 +0 = 120 / 7 = 17.1C  
Median = { 0,20,20,20,20,20,20 } = 20;

If the number of readings is even you should take the average of the middle 2; therefor an uneven number is easier to handle.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 10:18pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/6 "2011-02-19T22:18:14Z")

</div>

You can probably improve results somewhat using the internal Atmega 1V1 reference, but you may have to add an analog amplifier stage to get decent accuracy from this sensor. An unstable power supply may also be an issue. As it is now a single bit variation is equivalent to 0.5 degrees and this is likely to give you fluctuations.

You can try the 1V1 reference and calculate a running average (no delay's) from something like 4096 samples to see if a software approach is sufficient.

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 19, 2011, 10:42pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/7 "2011-02-19T22:42:14Z")

</div>

> a running average (no delay's) from something like 4096 samples

How big should the window be? NB a running average only takes the last N readings into account... and keeping 4096 readings in memory might be too much for Arduino.

Or do you mean a 'normal' average?

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 10:54pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/8 "2011-02-19T22:54:12Z")

</div>

> robtillaart:
> 
> > a running average (no delay's) from something like 4096 samples
> 
> How big should the window be? NB a running average only takes the last N readings into account... and keeping 4096 readings in memory might be too much for Arduino.
> 
> Or do you mean a 'normal' average?

I use this formula and keep it accumulating between outputs.

```arduino
  sample_count++;
  val = analogRead();
  sample_avg = sample_avg + (val - sample_avg) / sample_count;

```

Wikipedia refers to this as cumulative running average.

> **[Moving average](https://en.wikipedia.org/wiki/Moving_average)**
>
> In statistics, a moving average (rolling average or running average or moving mean or rolling mean) is a calculation to analyze data points by creating a series of averages of different selections of the full data set. Variations include: simple, cumulative, or weighted forms.
> Mathematically, a moving average is a type of convolution. Thus in signal processing it is viewed as a low-pass finite impulse response filter. Because the boxcar function outlines its filter coefficients, it is called a b...

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 19, 2011, 11:19pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/9 "2011-02-19T23:19:19Z")

</div>

Good night

Thanks for all the replies.  
Hereby your posts, I've changed the code...

> int sample\_count;  
> float val;  
> float sample\_avg;  
> float temp;
> 
> void setup()  
> {  
> Serial.begin(9600); // start serial communication  
> }
> 
> void loop()  
> {
> 
> sample\_count++;  
> val = analogRead(1);  
> sample\_avg = sample\_avg + (val - sample\_avg) / sample\_count;
> 
> if (sample\_count\>=8){  
> temp=( 5.0 \* sample\_avg \* 100.0) / 1024.0;  
> Serial.print(temp,DEC);  
> Serial.println("º");  
> sample\_count=0;  
> }  
> delay(1000);  
> }

Have the following values... still get out of interval 0.5º...

24.4140625000Âº  
21.2402343750Âº  
22.3388671875Âº  
27.0385742187Âº  
22.0947265625Âº  
26.6113281250Âº  
19.0429687500Âº  
23.1323242187Âº  
22.6440429687Âº  
26.4282226562Âº  
22.3999023437Âº  
27.0385742187Âº  
20.6298828125Âº  
18.4936523437Âº  
20.0195312500Âº  
20.4467754364Âº  
18.5546875000Âº  
18.0664062500Âº  
20.4467773437Âº  
21.0571289062Âº  
22.5830078125Âº  
18.6767559051Âº

Please let me know  
Thanks on advance  
Best regards  
Pedro Ferrer

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 12:33am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/10 "2011-02-20T00:33:39Z")

</div>

THIS QUESTION _CAPslock_ has been up a few times... You are not the only one with this problem. The general solution seems to be the one mentioned: take a number of samples and use the average. But as you have noticed, the average fluctuates as well ☹

You can get a little better resolution by using the 1.1 volt voltage reference which gives 1.1/1024 = ?? instead of the standard 5/1024 =?? volts resolution. This limits the upper temperature one can measure though.

I tried both solutions and was not satisfied.

I did try putting a resistor in series with the signal from the transmitter, and that seemed to calm the variation (but not good enough for my taste). Maybe a really small capacitor together with that ? (there are suggestions on "filtering" the signal in the sensors datasheet).

I decided that the ADC sucked... at least for directly measuring small variations in room temperature with an analog sensor like that.

One thing I did not try was use the ADC Noise Canceler function(did know about it then and it was to complicated for me at that time anyway). Basically it puts the processor in sleep mode to reduce noise from the cpu and I/O :s when it makes the conversion (page 256 in my datasheet for the processor). Thats not for beginners though (I think).

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 2:00am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/11 "2011-02-20T02:00:23Z")

</div>

I would scope the output of the sensor. I will predict you will see a significant AC on the LM35 output signal, I have see this many times. The easiest way to solve it is to decouple it using a 0.1uf cap to gnd.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 5:39am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/12 "2011-02-20T05:39:48Z")

</div>

You're still averaging 8 samples. The difference comes from the count of samples, not the formula. The formula is needed to maintain mathematical precision across thousands of samples.

This is what I had in mind:

```cpp
int sample_count;
float val;
float sample_avg;
float temp;

void setup()
{
  Serial.begin(9600); // start serial communication
  analogReference(INTERNAL);
}

void loop()
{
  sample_count++;
  val = analogRead(1);
  sample_avg = sample_avg + (val - sample_avg) / sample_count;

  if (sample_count >= 4096){
    temp=(1.1 * sample_avg * 100.0) / 1024.0;
    Serial.print(temp,DEC);
    Serial.println("º");
    sample_count = 0;
    delay(1000); 
  }
}

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 8:56am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/13 "2011-02-20T08:56:09Z")

</div>

Good morning

Thanks to all!

> analogReference(INTERNAL);

not work on Mega (my case)... [http://www.arduino.cc/en/Reference/AnalogReference](http://www.arduino.cc/en/Reference/AnalogReference)

> INTERNAL: an built-in reference, equal to 1.1 volts on the ATmega168 or ATmega328 and 2.56 volts on the ATmega8 (not available on the Arduino Mega)

instead use

> INTERNAL1V1: a built-in 1.1V reference (Arduino Mega only)

At the moment I'm using the following code:

> int sample\_count;  
> float val;  
> float sample\_avg;  
> float temp;
> 
> void setup()  
> {  
> Serial.begin(9600); // start serial communication  
> analogReference(INTERNAL1V1);  
> }
> 
> void loop(){
> 
> sample\_count++;  
> val = analogRead(1);  
> sample\_avg = sample\_avg + (val - sample\_avg) / sample\_count;
> 
> if (sample\_count\>=4096){  
> temp=(1.1 \* sample\_avg \* 100.0) / 1024.0;  
> Serial.print(temp,DEC);  
> Serial.println("º");  
> sample\_count=0;  
> }  
> }

with the following results:

21.7517642974Âº  
21.8397789001Âº  
21.6071357727Âº  
21.6462440490Âº  
21.9182052612Âº  
21.5186367034Âº  
21.4956054687Âº  
21.5795688629Âº  
21.7270050048Âº  
21.7120819091Âº  
21.8656406402Âº  
21.7869682312Âº  
21.7573280334Âº  
21.3469219207Âº  
21.6581382751Âº  
21.6491451263Âº  
21.8310565948Âº  
21.8769569396Âº  
21.6874866485Âº  
21.4888286590Âº  
21.8148403167Âº  
21.6632823944Âº  
21.9248332977Âº  
21.7272529602Âº  
21.5622024536Âº  
21.6742362976Âº  
21.9223327636Âº  
21.7440147399Âº  
21.7992439270Âº  
21.8053760528Âº  
21.6359863281Âº  
21.6092872619Âº  
21.6726818084Âº  
21.7128028869Âº  
21.6772994995Âº  
21.7238197326Âº  
21.5995445251Âº  
21.6944599151Âº  
21.9314517974Âº  
21.9353237152Âº  
21.6809310913Âº  
21.6946468353Âº  
21.7912731170Âº  
21.7200946807Âº  
21.8130283355Âº  
21.7228450775Âº  
21.6906337738Âº  
21.7354259490Âº  
21.8063049316Âº  
21.7635898590Âº  
21.6838798522Âº  
21.8985519409Âº  
21.7086772918Âº  
21.8521080017Âº  
21.8069458007Âº  
21.6680202484Âº  
21.5060596466Âº  
21.6929054260Âº  
21.6416168212Âº  
21.6140098571Âº  
21.6849155426Âº  
21.6466236114Âº  
21.7007369995Âº  
21.8061904907Âº  
21.6499042510Âº  
21.6719341278Âº  
21.7773628234Âº  
21.6784534454Âº  
21.8603801727Âº  
21.8354701995Âº  
21.7990589141Âº  
21.7120246887Âº  
21.7960605621Âº  
21.5650711059Âº  
21.8893489837Âº  
21.6773605346Âº  
21.9319019317Âº  
21.7376194000Âº  
21.7940521240Âº  
21.7638874053Âº  
21.8846740722Âº  
21.6499366760Âº  
21.6243877410Âº  
21.6514186859Âº  
21.5869674682Âº  
21.5570831298Âº  
21.7493019104Âº  
21.7388210296Âº  
21.7910137176Âº  
21.6423130035Âº  
21.6636428833Âº  
21.4642677307Âº  
21.5848770141Âº  
21.8051662445Âº  
21.9307136535Âº  
21.5620422363Âº  
21.5547714233Âº  
21.5966053009Âº  
21.6848735809Âº  
21.4665508270Âº  
21.5726337432Âº  
21.5996551513Âº  
21.7107944488Âº  
21.6048946380Âº  
21.6620063781Âº  
21.6681022644Âº  
21.6178131103Âº  
21.3954982757Âº  
21.4469547271Âº  
21.7632446289Âº  
21.6807022094Âº  
21.7202568054Âº  
21.7815170288Âº  
21.6968841552Âº  
21.7859973907Âº  
21.6573352813Âº  
21.6181240081Âº  
21.7958011627Âº  
21.4995384216Âº  
21.8133258819Âº  
21.7820625305Âº  
21.9121074676Âº  
21.7330188751Âº  
21.8351535797Âº  
21.8324012756Âº  
21.6706733703Âº  
21.6437759399Âº  
21.7632808685Âº  
21.7751846313Âº  
21.6557731628Âº  
22.0018768310Âº  
21.6623477935Âº  
21.4358425140Âº  
21.4864177703Âº  
21.8115024566Âº  
21.6672458648Âº  
21.7172889709Âº  
21.7049694061Âº  
21.5239562988Âº  
21.7810649871Âº  
21.6769676208Âº  
21.7803306579Âº  
21.7806873321Âº  
21.6148014068Âº

Much, but much better now!!!

Now... I'm using the 1.1V reference... ok it works.  
But what will happen now the other analogue readings...like my LCD Buttons that enter on A0?

> **[Gravity: 1602 LCD Keypad Shield For Arduino - DFRobot](https://www.dfrobot.com/index.php?route=product%2Fproduct&path=53&product_id=51)**
>
> This is the very popular arduino LCD shield. It includes a 2x16 LCD display and 6 momentary push buttons for menu selection purposes.

Once again, thanks by your great help!  
Best regards  
Pedro Ferrer

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 20, 2011, 11:09am UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/14 "2011-02-20T11:09:42Z")

</div>

wrt the code:

- samplecount is not initialized to 0;
- sample\_avg is not initialized to 0.0 and not reset when samplecount is reset to 0

The formula used gives a different weigth to different readings,  
sample\_avg = sample\_avg + (val - sample\_avg) / sample\_count;

Note: the first counts for ~10%, the second for 5%, the 3rd for ~3%, 4th for 2.5% while the last counts for ~ 0.01% (spreadsheet wisdom).  
This means that the first 4 readings make up 20% of your avg , (11 -\> 30%; 50 -\> 50%) , so if there is a misreading in your first 4 readings it affects the final average quite much.

try the code below (closer to your original code) to determine the samples needed for a stable reading ; the output is comma separated so you can copy it into a spreadsheet and make a graph.

I expect that depending on the precision you will need between 50-500 samples iso 4096

```cpp
int sample_count = 0;
float sample_sum = 0.0;
float sample_avg = 0.0;
float temp = 0.0;

void setup()
{
  Serial.begin(115200); // start serial communication
  analogReference(INTERNAL1V1);
}

void loop()
{
  sample_count++;
  sample_sum += analogRead(1);

  Serial.print(sample_count);
  Serial.print(", ");  // sep
  sample_avg = sample_sum / sample_count;
  temp=(1.1 * sample_avg * 100.0) / 1024.0;
  Serial.print(temp,DEC);

  if (sample_count >= 4096)
  {
    sample_count = 0;
    sample_sum = 0;
  }
}

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 4:01pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/15 "2011-02-20T16:01:59Z")

</div>

> robtillaart:  
> wrt the code:
> 
> - samplecount is not initialized to 0;
> - sample\_avg is not initialized to 0.0 and not reset when samplecount is reset to 0
> 
> The formula used gives a different weigth to different readings,  
> sample\_avg = sample\_avg + (val - sample\_avg) / sample\_count;

All static variables in C not explicitly initialized by user code will be initialized to zero. This is part of the C/C++ language definition. Explicit initialization does no harm, but will generate additional code and increase the size of your program.

There is no need to reset sample\_avg as the formula assigns 100% weight to the difference once sample\_count gets reset (that is sample\_avg = val for the first sample).

A problem with the proposed change is that precision drops off as sample\_sum increases to the extent that additional samples eventually carry no weight. Running a test with print for every sample delays time between samples and so is not representative for how you would run the final program and results may be quite different.

In short, I would leave experiments regarding sampling theory to a project in itself as it is not trivial to determine what is best.

As for reading button states, you will have to change analogReference prior to reading and then change back once finished. A single read of button state may be sufficient and so this could be done when you reset the sample counter for your LM35.

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 4:52pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/16 "2011-02-20T16:52:23Z")

</div>

Hello

Thanks once again to all!

> As for reading button states, you will have to change analogReference prior to reading and then change back once finished. A single read of button state may be sufficient and so this could be done when you reset the sample counter for your LM35.

I understand that.  
Do and Undo state to analogReference, no problem.

At the moment I'm using the following lines code on temp sketch. It seems to me that is stable.

> int sample\_count;  
> float val;  
> float sample\_avg;  
> float temp;
> 
> void setup()  
> {  
> Serial.begin(9600); // start serial communication  
> analogReference(INTERNAL1V1);  
> }
> 
> void loop()  
> {  
> sample\_count++;  
> val = analogRead(1);  
> sample\_avg = sample\_avg + (val - sample\_avg) / sample\_count;
> 
> if (sample\_count \>= 4096){  
> temp=(1.1 \* sample\_avg \* 100.0) / 1024.0;  
> Serial.print(temp,3);  
> Serial.println(" C");  
> sample\_count = 0;  
> delay(1000);  
> }  
> }

Thanks on advance  
Best regards  
Pedro Ferrer

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 20, 2011, 4:55pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/17 "2011-02-20T16:55:03Z")

</div>

> All static variables in C not explicitly initialized by user code will be initialized to zero. This is part of the C/C++ language definition. Explicit initialization does no harm, but will generate additional code and increase the size of your program.

100% true, but it is no good coding practice. Always initializing vars prevents errors, as for local vars it is a must. Further if a platform does not proporly implements the language definition there is trouble.

> There is no need to reset sample\_avg as the formula assigns 100% weight to the difference once sample\_count gets reset (that is sample\_avg = val for the first sample).

Didn't see that, nice trick ...

> A problem with the proposed change is that precision drops off as sample\_sum increases to the extent that additional samples eventually carry no weight.

True (but only marginally for 4000 samples) if you use float for the sum as I proposed., the precision of a float is ~6 digits = 0-1.000.000; so if the sum exceeds this you loose significant digits, but these are lost anyway by the division by 4096.  
Better is to use a unsigned long to summerize the raw samples. In fact an unsigned long can hold minimal 2^32 / 2^10 = 2^22 = 4 M samples without loss of precision (until divided by samplecount)

> Running a test with print for every sample delays time between samples and so is not representative for how you would run the final program and results may be quite different.

True, but if the variation in the individual samples is "big" as one can read in original post, the code I posted will give an indication of how much samples are needed for a certain precision and i'm quite confident (but could be wrong) that the number is lower than 4096. Imho it cannot be true that a sensor needs to be averaged over 4000 samples to become reliable.

> In short, I would leave experiments regarding sampling theory to a project in itself as it is not trivial to determine what is best.

It allways depend on the project requirements and the sensor used.

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 20, 2011, 5:01pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/18 "2011-02-20T17:01:49Z")

</div>

A small test shows no loss of precision when using a float for 4096 samples.

```cpp
void setup() 
{
  Serial.begin(115200);
  Serial.print("start");
}

unsigned long sumL = 0;;
float sumF = 0;
int t = 0;

void loop()
{
  unsigned long start = millis();
  for (int i = 0; i< 4096; i++)
  {
    t = 1024; //analogRead(A0);  // 1024 = max sample value + 1 !!
    sumL += t;
    sumF += t;
  }
  Serial.println(millis() - start);
  Serial.println(sumF);
  Serial.println(sumL); 
  sumL = 0;
  sumF = 0;
  while(1);
}

```

---

<div class="post-metadata">

**Author:** ![system](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/system/32/1140315_2.png) [@system](https://forum.arduino.cc/u/system)\
**Post date:** [February 20, 2011, 5:54pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/19 "2011-02-20T17:54:27Z")

</div>

> robtillaart:  
> A small test shows no loss of precision when using a float for 4096 samples.

The loss of precision comes from float data type limitations when you add a high value (sum) to a small value (single sample). This is because floats are normalized and can only maintain precision with respect to its exponent. If you change sum to an integer type, you avoid this issue, but risk overflowing the sum variable sooner. Also if the analog integral stays close to zero (such as with a gyro and accelerometer), your proposal works fine.

What I proposed is often preferred when averaging runs continuously for the lifetime of the application (temperature is a good example). An initial test is done to determine a reasonable number of samples required for a target precision/accuracy. Once you reach this count (lets say 256), you simply stop incrementing sample\_count so that each additional sample carries an equal weight. sample\_count then becomes a means to control sensitivity to change. A high max count equals low sensitivity whereas a low max count will respond quickly to change.

---

<div class="post-metadata">

**Author:** ![robtillaart](https://dub1.discourse-cdn.com/arduino/user_avatar/forum.arduino.cc/robtillaart/32/1098811_2.png) [@robtillaart](https://forum.arduino.cc/u/robtillaart)\
**Post date:** [February 20, 2011, 7:22pm UTC](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872/20 "2011-02-20T19:22:29Z")

</div>

> The loss of precision comes from float data type limitations when you add a high value (sum) to a small value (single sample). This is because floats are normalized and can only maintain precision with respect to its exponent. If you change sum to an integer type, you avoid this issue, but risk overflowing the sum variable sooner.

I know the theory - including the risks, my sample sketch only shows that adding up 4096 AnalogRead() samples (as was proposed) does not show this effect in practice when using a float for ("normal") averaging.

> What I proposed is often preferred when averaging runs continuously for the lifetime of the application (temperature is a good example). An initial test is done to determine a reasonable number of samples required for a target precision/accuracy. Once you reach this count (lets say 256), you simply stop incrementing sample\_count so that each additional sample carries an equal weight. sample\_count then becomes a means to control sensitivity to change. A high max count equals low sensitivity whereas a low max count will respond quickly to change.

Agree 100%,

[Next page](https://forum.arduino.cc/t/lm35dz-temperature-sensor-big-differences-while-reading-it/52872.md?page=2)
