Another running average that may be useful to all. This one will work even if you do not have floating point. However, you need to be able to handle large numbers or size the buffer appropriately that it doesn't overflow 'sum' while summing. Of course, you need way more ram than the Avg = (Avg*(n-1)+adcval)/n formula which is good for Ram Constrained systems.
Code:
Pseudo code.
NumOfSamples equ 16
AdcVal Word ' adc reading is placed here
Samples Word [NumOfSamples] ' rolling buffer having NumOfSamples of AdcReading (must retain value between calls to R_Average)
Index var byte ' next position where the sample will be put (must retain value between calls to R_Average)
Sum var long ' gross sum of all the samples (must retain value between calls to R_Average)
RA_Init: ' initialize the running average
Index = 0
Sum =0
return
' enter with A
R_Average:
sum = sum - Samples[Index] ' remove the oldest sample from the sum
sum = sum + AdcVal ' add in the latest sample to sum
Samples[Index] = AdcVal ' and save it in the buffer too
Index = Index+1 ' move the index
If Index > NumOfSamples then Index = 0 ' wrap around if needed
return sum / NumOfSamples ' the running average
Caller has to initiate with RA_Init before using the R_Average routine. I hope you will excuse my pseudo code since I am a bit rusty on my PBP at this moment.
Bookmarks