Go Down

Topic: decimal point in temp reading (Read 2 times) previous topic - next topic

Nick Gammon

Or the forum settings could be changed to allow larger posts...  ;)

I don't want to see lengthy posts of mindless gibberish, personally. ;)

That's why the limits are there.


What is wrong with it?

We can try to find out what it does by seeing what it actually calculates after the first few times round the loop.
float AvrageTemp(int analog_pin){
float averageTemp = 0; // create a float to hold running average
for (int i = 1; i < 1000; i++) // start at 1 so we dont divide by 0
    averageTemp += ((Thermister(analog_pin) - averageTemp)/(float)i); // get next sample, calculate running average
return averageTemp; // return average temperature reading

To make this briefer for me to type I'll refer to the avergeTemp calculated when at step i as just avgi (e.g. avg1, avg2 etc) and the sequence of Thermistor readings as T1, T2, etc.
In my version, avg0 is initialized to zero.
Therefore the result of avg1 = (T1 - avg0)/1 = T1. This one is correct. The average of one reading is just that reading.
Step 2: avg2 = (T2 - avg1)/2 = (T2 - T1)/2. This is clearly wrong. The average of the two values should be (T2 + T1)/2
Step 3: avg3 = (T3 - avg2)/3 = (T3 - (T2 - T1)/2)/3 = ( 2*T3 - T2 + T1)/6. Nope.
Step 4: avg4 = (T4 - avg3)/4 = (T4 - (2*T3 - T2 + T1)/6) / 4 = (6*T4 - 2*T2 + T2 - T1)/24. It's getting worse.
If you assume that all the readings are identical and equal a value T, then at any step of the loop it should produce the value T as the average but after step four, if each Ti = T, then the result of the fourth step is T/6. Not even close to the average.
So, what is wrong with it is that it doesn't compute an average - "running" or otherwise.
There's also one other minor booboo in the code. The for loop only goes round 999 times - not 1000

/ the proper way would be?

If it is supposed to produce the average of one thousand consecutive readings then it could be done like this:

Code: [Select]

float AvrageTemp(int analog_pin){
  // Holds the average
  float averageTemp = 0;
  // Calculate the average of one thousand consecutive readings of the thermistor
  for (int i = 0; i < 1000; i++) {
    averageTemp += Thermister(analog_pin)/1000.;
  // return average temperature reading
  return averageTemp;


Go Up