
#define SAMPLE_COUNT    16

/*-----------------------------------------------
Maintain STATIC copies of the sample table,
the index into it, and the current total.

sample_tab is simply an array of the last
SAMPLE_COUNT samples.

ndx is the index where the new_sample will go.

ttl is the total of all samples in sample_tab
(sample_tab[0] + sample_tab[1] + ...).
-----------------------------------------------*/
static int sample_tab [SAMPLE_COUNT];
static unsigned char ndx=0;
static long ttl = 0;

/*-----------------------------------------------
-----------------------------------------------*/
int moving_avg (
  int new_sample)
{
/*-----------------------------------------------
Subtract the oldest sample from ttl.
Add the new_sample to ttl and put the new_sample
into the sample_tab.
-----------------------------------------------*/
ttl += sample_tab [ndx];
ttl += new_sample;
sample_tab [ndx] = new_sample;

/*-----------------------------------------------
Increment the index and handle the ending
boundary.
-----------------------------------------------*/
if (++ndx >= SAMPLE_COUNT)
  ndx=0;

/*-----------------------------------------------
Return the average of the samples in the table.
-----------------------------------------------*/
return (ttl/SAMPLE_COUNT);
}
