[sdiy] ADC filtering (was A/D converter ...)
Matthew Smith
matt at smiffytech.com
Sun May 8 02:19:13 CEST 2011
Quoth dan snazelle at 08/05/11 08:58...
> could anyone point me to a (maybe in C) code example of how this would work?
> or just some more info?
>
> would it be sort of like putting using a FOR statement to let it read 4 values, then average them?
> (do you use the un-averaged AND averaged readings? or do you throw out the first four?
I'm a bit curious how chopping the oldest value would be achieved
without using an array or circular buffer.
Below is a 'desktop C' stab at how I'd do it. (The volatile declarations
are there so I don't forget them when in an embedded context - we may be
calling avg4() from an ISR, thus volatile required.)
Still wonder if there isn't a more efficient way than using the array.
Cheers
M
#include <stdio.h>
volatile unsigned int avgreg[4]={0, 0, 0, 0};
volatile unsigned int avg_counter=0;
unsigned int avg4(unsigned int);
int main(void)
{
unsigned int x, result;
result=avg4(10);
result=avg4(12);
result=avg4(8);
/*
...etcetera.
Obviously, you'd actually do somethign
with the value of result.
*/
return(0);
}
unsigned int avg4(unsigned int i)
{
unsigned int avgtmp;
avgreg[3]=avgreg[2];
avgreg[2]=avgreg[1];
avgreg[1]=avgreg[0];
avgreg[0]=i;
/* Insufficient to make average, return input. */
if (avg_counter<3)
{
avg_counter++;
return(i);
}
avgtmp=avgreg[0]+avgreg[1]+avgreg[2]+avgreg[3];
avgtmp>>=2;
return(avgtmp);
}
More information about the Synth-diy
mailing list