Distance Sensor. Calculating running median and Average I'm trying to smooth out values for my IR distance sensor through running median filtering and a running average. I've tried to do the averaging, but my values don't seem correct and I am confused about how I would do the median filtering. I am also using timer interrupts and I don't want to use libraries when calculating the average and median. I've attached the code where I attempted to calculate the average. 

int analogpin=5;
int sum=0;
int index=0;
int averead=0;
const int numreadings=9;
int i;
int timer1_counter;
int adc_val;
int int_flag;
int int_array[9];
float V;


void setup() {

int_flag=0;

Serial.begin(9600);
pinMode(analogpin,OUTPUT);
for(i=0; i&lt;=8; i++){
  int_array[i]=0;
}

noInterrupts();           //

  TCCR1A = 0;
  TCCR1B = 0;


timer1_counter = 59286;  

  TCNT1 = timer1_counter;   
  TCCR1B |= (1 &lt;&lt; CS12);    
  TIMSK1 |= (1 &lt;&lt; TOIE1);   
  interrupts();             
}

ISR(TIMER1_OVF_vect)        
{
  TCNT1 = timer1_counter;   
  int_flag=1;               
    }

void loop() {


  if (int_flag==1){
    adc_val=analogRead(A2);
    V=5.0*adc_val/1023.0;
    analogWrite(analogpin,adc_val/4);
    }
    sum=sum-int_array[i];
    int_array[i]=analogRead(A2); 
    sum=sum+int_array[i];
    index=index++;
    if(i==9){
      i=0;
    }
    averead=sum/numreadings;
    Serial.print("\n"); Serial.print("Average Filter Reading: "); 
Serial.println(averead);
    delay(1);
    }
There are two main problems with your program. The first is noted in
Gerben's comment: you (attempt to) increment index (with a bad
syntax), while you should be incrementing i instead. The second
problem is these lines:



for (i = 0; i &lt;= 8; i++) {
    int_array[i] = 0;
}


Fix the index vs. i confusion, remove the lines above, and your
program should work.

Explanation: The first point should be obvious, I hope. I am
discussing here the second issue. At the end of the loop above, the
index i has the value 9. Later, in loop(), and assuming you fixed
the first issue, the program does

i++;
if (i == 9) {
    i = 0;
}


and i has the value 10. From there i will continue incrementing, and
you are always writing outside of the array.

The root of the problem is that you used the same variable i for two
different purposes. There are several solutions to this:


use different variable names for different purposes
use local variables whenever applicable (here: in setup())
be defensive in your tests: instead of if (i == 9) write
if (i &gt;= 9), but note that this alleviates but does not completely
solve the problem
remove the initialization of the array altogether.


I suggest removing the initialization because the array is a global
variable and, per the C++ standard, if not explicitly initialized it is
implicitly initialized to zero, so your initialization is redundant.