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 <= 8; i++) {
int_array[i] = 0;
}
noInterrupts();
TCCR1A = 0;
TCCR1B = 0;
timer1_counter = 59286;
TCNT1 = timer1_counter;
TCCR1B |= (1 << CS12);
TIMSK1 |= (1 << 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);
}
index=index++;does nothing. Either useindex=index+1;ofindex++. Also, you are usingifor the array-index, but only (try to) incrementindex. I think that should bei=i+1. Because nowhere elseiis changed, you always overwrite the same element in the array. – Gerben Mar 30 '19 at 12:32int_flagin an ISR, shouldn't it bevolatile? Also in loop() you never reset it to 0. This can't be right... – dda Jan 09 '24 at 15:21