Yahoo Groups archive

AVR-Chat

Index last updated: 2026-04-28 22:41 UTC

Message

Re: [AVR-Chat] Moving average filter

2009-07-17 by Andreas Stemmer

Hallo Roman,

there are two things you could do to speed up the calculation significantly. First of all, it's not necessary to shift the data through the array with each update cycle. Instead, keep the data in its position and just use an index to the oldest element (like a ring buffer).

It's also not necessary to calculate the sum which each update. Instead, save the old sum and just remove the oldest element and add the new element with each update.

Something like (untested!):

#define FILTERSIZE 16
static unsigned char mafData[FILTERSIZE];
static unsigned char mafIdx;
static unsigned int mafSum;

void mafInit(void)
{
    int i;
    for (i=0; i<FILTERSIZE; i++)
        mafData[i] = 0;
    mafSum = 0;
}

unsigned char mafUpdate(unsigned char data)
{
    /* remove oldest element */
    mafSum -= mafData[mafIdx];

    /* add new element */
    mafData[mafIdx] = data;
    mafSum += mafData[mafIdx];

    /* increment index */
    if (++mafIdx >= FILTERSIZE)
        mafIdx = 0;

    /* return moving average */
    return (mafSum/FILTERSIZE);
}

Depending on your data, returning the filter value as float or at least doing some proper rounding after division could be sensible.

Andreas


-------- Original-Nachricht --------
> Datum: Fri, 17 Jul 2009 12:07:14 +0300
> Von: "Антощенков Роман Викторович" <djantoxa@rambler.ru>
> An: AVR-Chat@yahoogroups.com
> Betreff: [AVR-Chat] Moving average filter

> Hello!
> 
> I using WinAVR 20090313 and ATMega32.
> I write code for time critical application.
> There is a moving average filter algorithm.
> 
>     unsigned char data    = 0;
>     unsigned char i       = 0;
>     unsigned char mafinit = 0;
>     unsigned int  mafsum  = 0;
>     unsigned char mafdata[16];
> 
>     if (!mafinit)
>     {
>       for (i = 0; i < 16; i++)
>         mafdata[i] = data;
>       mafinit = 1;
>     }
> 
>     for (i = 0; i < 15; i++)
>     {
>       mafdata[i] = mafdata[i+1];
>       mafsum += mafdata[i];
>     }
>     mafdata[15] = data;
>     mafsum += data;
>     data = mafsum / 16;
> 
> Are there any ways to speedup algorithm?
> 
> -- 
> Best regards,
> Roman Antoshchenkov
> mailto:djantoxa@rambler.ru

Attachments

Move to quarantaine

This moves the raw source file on disk only. The archive index is not changed automatically, so you still need to run a manual refresh afterward.