Reputation: 33
I am using a PIC and a proximity sensor to read the distance in cm away from an object.
The result is stored in
Distance = Rf_Rx_Buff[6].
Basically instead of using that result I want to implement a filter which takes 10 readings, averages them out and only allows the average to be read out in Rf_Rx_Buff[6] .
Could anyone guide me on how to implement this.
Upvotes: 2
Views: 109
Reputation: 154075
At least 3 approaches:
Read 10 values and return the average (easy)
unsigned Distance1(void) {
unsigned Average_Distance = 0;
for (int i=0; i<10; i++) {
Average_Distance += Rf_Rx_Buff[6];
}
Average_Distance = (Average_Distance + 5)/10; // +5 for rounding
return Average_Distance;
}
Read once, but return the average of the last 10 reads:
unsigned Distance2(void) {
static unsigned Distance[10];
static unsigned Count = 0;
static unsigned Index = 0;
Distance[Index++] = Rf_Rx_Buff[6];
if (Index >= 10) {
Index = 0;
}
Count++;
if (Count > 10) {
Count = 10;
}
unsigned long Average_Distance = 0;
for (int i=0; i<10; i++) {
Average_Distance += Distance[i];
}
Average_Distance = (Average_Distance + Count/2)/Count;
return Average_Distance;
}
Read once, but return the the running average (digital low pass filter):
unsigned Distance3(void) {
static unsigned long Sum = 0;
static int First = 1;
if (First) {
First = 0;
Sum = Rf_Rx_Buff[6] * 10;
} else {
Sum = Rf_Rx_Buff[6] + (Sum*9)/10;
}
return (Sum + 5)/10;
}
Other simplifications and approaches possible,
Upvotes: 1
Reputation: 2124
You could do it that way:
1.) Develop a function that calculates the average.
int calc_average(int *sensor_values, int number_sensor_values) {
int result = 0;
for(char i = 0; i < number_sensor_values; ++i) {
// calculate average
result += *sensor_values++...
....
}
....
return result;
}
2.) Read 10 sensor data and store the data in an array (sensor_values
).
3.) Call your calc_average
function and pass the sensor_values
array to get the result.
Upvotes: 0