News:

Let's find out together what makes a PIC Tick!

Main Menu

continuous or moving averaging

Started by Yves, Dec 21, 2023, 11:13 AM

Previous topic - Next topic

Yves

Hello,

I battling to put a routine together for a continuous or moving  averaging on 4 data points. I have data coming at approximately every second let call the time T and a value which we can call Val. I like to average them in groups of 4 seconds but not in fix group but in sort of moving average. I any one one have a simple routine that demonstrate that? Thank you for your time

Kind regards,

Yves

     
Yves

trastikata

Hello Yves,

is this what you need or I misunderstood the question?

Dim bFifoBuffer[4] As Byte      'FIFO Buffer
Dim bData As Byte               'New data
Dim bAverage As Byte            'Moving average

Main:
    While 1 = 1
        'Do something
        bAverage = AverageFifoBuffer(bData)
    Wend
   
Proc AverageFifoBuffer(bDataIn As Byte), Byte
    Dim bTemp As Byte
    Dim wTemp As Word
   
    Clear wTemp
    For bTemp = 3 DownTo 1 Step -1
        'Shift FIFO buffer
        bFifoBuffer[bTemp] = bFifoBuffer[bTemp - 1]
        'Accumulate data
        wTemp = wTemp + bFifoBuffer[bTemp]
    Next
   
    'Write latest data to FIFO
    bFifoBuffer[0] = bDataIn
    'Add the new data to the accumulator
    wTemp = wTemp + bDataIn
    'Average data
    Result = wTemp >> 2
EndProc

Sommi

Hi Yves,

this snippet uses a buffer that is initialised with zero, incoming data is added and the last value of the shift length is subtracted.
It's easy to adjust to 2,4,8,16 etc. length

'************************************************
dim s1 as byte
dim s2 as byte
dim s3 as byte
dim s4 as byte
dim inputbyte as byte
dim bucket as word
dim average as byte

s1=0
s2=0
s3=0
s4=0

bucket=0

Main:
   while 1=1
      ;somhow get inputbyte
      bucket = bucket + inputbyte
       bucket = bucket - s4
      s4=s3:s3=s2:s2=s1:s1=inputbyte
      average=bucket/4
   wend
'*****************************************************

Regards Sommi
KISS - keep it simple and stupid

John Drew

#3
Another approach that Les wrote amounted to bringing many samples into a RAM table, sorting the table and  then selecting the mean. I tried it and it worked well.
Generally I use the approach suggested here which is fine if the numbers are small. Otherwise the summing variable ( bucket in the example from Sommi) can be exceeded.
John