[sdiy] ADC filtering (was A/D converter ...)

Olivier Gillet ol.gillet at gmail.com
Sun May 8 02:36:38 CEST 2011


> 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.

It can be simpler:
* Don't compute the sum at each call to avg. Add/subtract to a running sum.
* Use a circular buffer to store the values instead of moving data
around the array.

uint16_t history[16];
uint8_t ptr;
uint16_t sum;

uint16_t avg16(uint16_t v) {
  sum -= history[ptr];  // Remove the least recent value from the sum
  sum += v;  // Add the most recent value to the sum
  history[ptr] = v;  // Store the most recent value in the history array
  ptr = (ptr + 1) % 16;  // Cycle the history pointer
  return sum / 16;
}



More information about the Synth-diy mailing list