2010-04-21 26 views
0

我有很多(〜100左右)濾波器係數藉助一些Matlab和Excel計算出來,我想將它們轉儲到一個通用的頭文件中,但我不確定要做到這一點的最佳方法是什麼。我開始了像這樣:最清潔的方式來存儲C頭中的濾波器係數列表

#define BUTTER 1 
#define BESSEL 2 
#define CHEBY 3 
#if FILT_TYPE == BUTTER 
    #if FILT_ROLLOFF == 0.010 
     #define B0 256 
     #define B1 512 
     #define B2 256 
     #define A1 467 
     #define A2 -214 
    #elif FILT_ROLLOFF == 0.015 
     #define B0 256 
     #define B1 512 
// and so on... 

但是,如果我這樣做,他們都推到一個頭,我需要包括它之前設置在我的源代碼的條件語句(FILT_TYPEFILT_ROLLOFF),這似乎有點討厭。更重要的是,如果我有2種不同的過濾器需要不同的滾降/過濾器類型,它將無法工作。我可以在這個係數文件中使用我的5個係數(A1-2,B0-2),但是它仍然看起來是錯誤的,不得不在代碼中插入一個#include

編輯: 這是一個非常小的(2-4K)代碼空間的嵌入式8位處理器。我似乎無法通過將它們存儲到結構數組中來實現這一點,因爲它消耗的空間是不可接受的。即使聲明它們都是不變的,我的編譯器不會'優化它們',所以我留下了超過1.2K額外二進制數據的陰影。

以下不起作用。

typedef struct { 
    int16_t b0, b1, b2, a1, a2; 
} filtCoeff; 

const filtCoeff butter[41] = { 
    {256,512,256,467,-214}, 
    {256,512,256,444,-196}, 
    {255,512,255,422,-179}, 
    // ... 
}; 
const filtCoeff bessel[41] // ... 

回答

2

您可以使用令牌串聯將它們設置爲參數一個宏。

#define BUTTER 1 
#define BESSEL 2 
#define CHEBY 3 

#define ROLLOFF_0_010 1 
#define ROLLOFF_0_015 2 

// BUTTER, ROLLOFF_0_010 
#define B0_11 256 
#define B1_11 512 
#define B2_11 256 
#define A1_11 467 
#define A2_11 -214 

// BUTTER, ROLLOFF_0_015 
#define B0_12 256 
#define B1_12 512 
// ... 

#define B0_(type, rolloff) (BO_##type##rolloff) 
#define B1_(type, rolloff) (B1_##type##rolloff) 
#define B2_(type, rolloff) (B2_##type##rolloff) 
#define A1_(type, rolloff) (A1_##type##rolloff) 
#define A2_(type, rolloff) (A2_##type##rolloff) 

/* 
* This two level define is so that the parameters to these macros 
* get run through the macro process. That is, B1_(BUTTER, ROLLOFF_0_010) 
* evaluates as B1_BUTTERROLLOFF_0_010, while B1(BUTTER, ROLLOFF_0_010) 
* evaluates as B1_11 and thus as 256. 
*/ 

#define B0(type, rolloff) B0_(type, rolloff) 
#define B1(type, rolloff) B1_(type, rolloff) 
#define B2(type, rolloff) B2_(type, rolloff) 
#define A1(type, rolloff) A1_(type, rolloff) 
#define A2(type, rolloff) A2_(type, rolloff) 

B1(BUTTER, ROLLOFF_0_015)現在等效512。然後你可以用宏來構建更復雜的東西。例如: -

#define CROSSPRODUCT(type, rolloff, values) \ 
    B0(type, rolloff) * ((values)[0]) + \ 
    B1(type, rolloff) * ((values)[1]) + \ 
    ... 

你也可以把你的代碼在另一個文件中,並使用TYPEROLLOFF。然後只需#defineTYPEROLLOFF幷包含其他文件。我認爲我更喜歡使用宏。

3

將濾波器係數放入一個結構數組中。我只想將數組指針的聲明放在.h文件中,並將它們定義在鏈接的特定.c文件中。

+0

雖然這排除了一些可能的優化,但它絕對是一個更乾淨的解決方案。 – xtofl 2010-04-21 19:26:50

+0

忘了提及這是針對小型8位嵌入式目標,所以40個滾降* 3個類型* 5個coeffs * 2個字節= 1200個字節的數據消耗掉了我大部分的Flash。 – 2010-04-21 19:57:50