Running Average. Easy.

denisboc

New Member
Hello all. Thought I would post this program snippet in hope someone finds it useful (and easy).

This program is basically to give me a true running average of the last 100 readings from a DS18B20.

It builds and stores the last 100 readings into memory. Once it has it's 100 memory places filled it throws out the oldest value and writes the newest value in.

It is important to note I don't need to read and add up all the values stored to find the current SUM of the values. i.e SUM = SUM - (Oldest Value) + (Newest Value).
The memory array just enables me to locate oldest value and replace it with newest value.

'Basically we keep last NUM readings in memory. In this case 100.
'Number of readings stored depends on keeping the Sum of the stored values less than a word. '255x255=65,025.
For me using values between 0 and 640 i.e DS18B20 0 -> 40'C in a temperature controller.
'65025/640 = 101 that's good for me . Just need to check that includes at least 2 periods of the sine like curve about the target temperature.

'The Average = SUM / NUM(ber) of values stored

'At program start up I don't have all the values stored so I Load them as I read them and still Average = SUM/NUM works. As NUM increases and hits 100 then it kinda becomes a fixed variable.

SYMBOL PTR = b1 'Pointer to memory locations
SYMBOL NUM = b2 'Number of values stored
SYMBOL tEggs = w2 'latest Temperature value
SYMBOL OldT = w3 'Oldest Temperature Value stored
SYMBOL Avg = w4 'average
SYMBOL SUM = w5 'Sum of Values Stored
SYMBOL Egg_Thm = C.0 'egg thermometer DS18B20
'SYMBOL OldT = w3

NUM = 0
main:

for PTR = 26 to 224 step 2 '
readtemp12 Egg_Thm, tEggs ' read Egg_Thm into word 6'read tEggs
SUM = SUM + tEggs
if NUM < 100 then 'Still building our SUM so don't read OldT
inc NUM
else
NUM = 100 'Have filled our SUM so need to read OldT
read PTR, word OldT 'and take it's value off SUM
SUM = SUM - OldT
endif

Avg = SUM / NUM '

write PTR, word tEggs 'do this each time regardless after having read OldT

'sertxd("NUM =,",#NUM,",PTR =,",#PTR,",tEggs,=",#tEggs,"/16,OldT,=",#OldT,"/16,SUM,=",#SUM,"/16,Avg,=",#Avg,"/16",13,10) 'good for straight to excel (see below)


next PTR

goto main

'Just a little trick I use when I am exporting to Excel. I let Excel do the maths. Instead of writing #tEggs into a cell and getting the DS18B20 word 472 I write to the cell =#tEggs/16 and get 29.5 into the cell. Just saves a lot of program space sometimes.

Thus my excel sheet looks like this
NUM =
9​
PTR =
42​
tEggs
29.25​
OldT
0​
SUM
263.625​
Avg
29.25​
NUM =
100​
PTR =
56​
tEggs
29.5625​
OldT
29.5625​
SUM
2951.5​
Avg
29.5​

rather than this.
NUM =
100​
PTR =
26​
tEggs=
472​
OldT=
465​
SUM=
46552​
Avg=
465​

I hope someone finds it helpful.
regards Denis
 
Top