2014-11-06 73 views
2

我正在使用PIC和接近传感器来读取距物体的距离(厘米)。过滤器读数PIC

结果存储在

距离= Rf_Rx_Buff [6]。

基本上没有使用那个结果,我想实现一个过滤器,它需要10个读数,将它们平均,只允许平均值在Rf_Rx_Buff [6]中读出。

任何人都可以指导我如何实现这一点。

+0

什么是你的问题?读取该值10次并计算移动平均值。 – 2014-11-06 14:58:33

+0

是的,但那就是我正在努力,如何实现代码 – NewLook 2014-11-06 15:14:10

回答

1

至少有3种方法:

  1. 读取10个值,并返回平均值(容易)

    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; 
    } 
    
  2. 阅读一次,但返回最后10的平均读取:

    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; 
    } 
    
  3. 只读一次,但返回正在运行的平均值(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; 
    } 
    

其他简化和方法可能,

+0

谢谢1号作品完美 – NewLook 2014-11-06 16:10:38

0

你可以这样做:

1.)开发一个函数来计算平均值。

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.)阅读10的传感器数据并且将数据存储在一个阵列(sensor_values)。

3.)打电话给你的calc_average函数,并通过sensor_values数组得到结果。