2014-11-06 23 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數組得到結果。