Filter for rotary encoder
Moving Average

When calcuating the real time moving average of some samples it's always a good idea dividing the sum by 4, 8, 16, etc using the C shift operator.
That allows you to use integer arithmetic instead of floating point one which is way slower. This is especially true if you make calculation in an interrupt function.
Yet, the average variable used should be of a bigger size than the samples.
If samples are &quot;unsigned short&quot; than the average variable should be &quot;unsigned long&quot;.
Example:
unsigned short samples[256];
unsigned long average;
int i;

average = 0;
for (i = 0; i &lt; 8; i++)
{
  average += (unsigned long) samples[i];    
}

average &gt;&gt;= 3; 

Type cast is necessary. Don't trust your C compiler.

Interrupts and Critical Sections

If your capture and compare peripheral fires an interrupt at every double edge detection and the pulse width is evaluated in the interrupt function, than calculate the moving average within the the interrupt function (foreground) and not in the main() function (background).