0

I'm writing a C++ program library for my Arduino. The library is for a DTMF decoder. I'm having a problem when it comes to adding two detected and validated tones together in order to return the corresponding button.

I call the function below twice (it's not entirely finished but you'll hopefully get my logic). If I initialise the values R1 & R2 to 0 then they overwrite each other on the second call. If I don't initialise them at all I get a run time check error.

I've spend at 40+ hours trying to figure this out (I'm a very basic level coder!). Any help would be greatly appreciated!

    int DTMF::validate(void)
    {
        int threshhold = 9000;
        int i;
        int x;
        int y;
    //  int high[7];

        for(i=0; i<7; i++)
        {
            if(magnitude[i] > threshhold)
            {
                return(i);  
            }
        }
    }

unsigned char DTMF::buttonPressed(void)
{
    int validatedFreq = validate();
    cout << "valid is returning: " << validatedFreq << endl;
    int R1;
    int R2;

    switch(validatedFreq)
    {

        case 0:
            R1=1;
            cout << "DEBUG:This is case 1 R1 output: " << R1 << endl;
            break;

        case 1:
            R1=2;
            break;

        case 2:
            R1=3;
            break;

        case 3:
            R2=4;
            cout << "DEBUG:This is case 3 R2 output: " << R2 << endl;
            break;

        case 4:
            R2=5;
            break;

        case 5:
            R2=6;
            break;

        case 6:
            R2=7;
            break;
    }

    if(R1==1 && R2==4)
    {
        cout << "DEBUG:The value of R1 is " << R1 << " and the value of R2 is " << R2 << endl;
        return(button[0]);
    }
}
4

3 に答える 3

0

R1 と R2 は、関数内で宣言したため、ローカル変数です。これは、関数を呼び出すたびに初期化され、そのたびに R1 と R2 が 2 つの新しい int 変数になることを意味します。

関数の異なる呼び出し間でそれらの値を同じに保ちたい場合は、それらを として宣言できますstatic。これにより、プログラムを実行するたびに一度だけ初期化されるようになります。あなたはそれを行います

static int R2;

于 2013-04-20T16:56:18.517 に答える
0

R1 と R2 はローカルであり、DTMF::buttonPressed 関数に対して自動的に実行されるため、呼び出し間で保持されません。

それらを初期化しない場合は、それらに意味のある値があると仮定する前に、それらを割り当てる必要があります。ただし、スイッチはそれらの 1 つだけを割り当てます。しかし、後で次のように両方を使用するふりをしますif

その時点で観察できる動作が何であれ、未定義です。

于 2013-04-20T16:58:59.607 に答える
0

クラスメンバーに変更する必要がR1あります(ヘッダーに移動します)。次に、コンストラクターでそれらをゼロに初期化し、前に両方がゼロでないかどうかを確認する必要があります。このような:R2DTMFif(R1==1 && R2==4)

// header:
class DTMF {
...
int R1;
int R2;
}
// cpp
DTMF::DTMF() : R1( 0 ), R2( 0 ) { ... }

unsigned char DTMF::buttonPressed(void)
{
    int validatedFreq = validate();
    cout << "valid is returning: " << validatedFreq << endl;
    //int R1;
    //int R2;

    // fill R1 or R2 exactly as you did

    if ( R1 != 0 && R2 != 0 && R1==1 && R2==4 ) {
        ...
        R1 = R2 = 0;
    }
于 2013-04-20T16:59:13.483 に答える