2017-06-30 11 views
-2

単に、最初にデジタル読み取りがトグル値を取得する場合、サブルーチンを実行するためのカウンタを作成したいと思います。しかし結果は、 "aFunction"が複数回(繰り返し)実行されることを示しています。voidループ内で関数を1回だけ実行する方法は?

コード:

int lastState = 1; 

void setup() { 
    Serial.begin(115200); 
} 

void loop() { 
    int currentState = digitalRead(D5);  
    if (currentState == 1) { 
     if (currentState = !lastState) { 
      aFunction(); 
     } 
     lastState = !lastState; 
    } 
    Serial.println("Still running loop");  
    delay(2000); 
} 

void aFunction() { 
    Serial.println("in a function"); 
} 
+0

何丁度あなたがあなたの問題に達成したいですか? – Sma

+1

あなたのループはループしません。何度も呼び出されない限り、何回も実行されることはありません。 –

+2

@GradyPlayerの開発では、開発者はループの機能を何度も繰り返す方法を追加しました。 – Sma

答えて

0

あなたはそれが一度実行されています知らせるための変数が必要です。

int lastState = 1; 
int runOnce = 0; 
void setup() { 

    Serial.begin(115200); 
} 

void loop() { 

    int currentState = digitalRead(D5);  
    if (currentState == 1) { 

     if (currentState = !lastState) { 
      if (runOnce == 0) 
       aFunction(); 
     } 
     lastState = !lastState; 
    } 

    Serial.println("Still running loop");  
    delay(2000); 
} 

void aFunction() { 
    Serial.println("in a function"); 
    runOnce = 1; 
} 

は、だから今、あなたのaFunction()は1にrunOnceフラグを設定し、それは今までになるまで再び実行されませんがifステートメントがloop()の内部にあるため、デバイスがリセットされます。

+0

ああ、お世話になりました。私は仕事があります:) –

+0

@JakaSatriaよろしくお願いします!私の答えがあなたを助けたならば、 "同意する"とupvoteは、他の人が同じような問題に直面するのを助けるでしょう、感謝します。 – TomServo

0

関数の実行を追跡し、currentState変数とともにチェックすると、目標を達成するのに役立ちます。

この変更にあなたのコードは次のようになります。

bool executed = false; 

void setup() { 
    Serial.begin(115200); 
} 

void loop() { 
    int currentState = digitalRead(D5);  
    if (currentState == 1 && executed == false) { 
     executed = true; 
     aFunction(); 
    } 
    Serial.println("Still running loop");  
    delay(2000); 
} 

void aFunction() { 
    Serial.println("in a function"); 
} 
+0

よくできています。非常にありがとう、あなたのアルゴリズムのためにありがとう:) –

+0

それが動作する場合、 "受け入れ"として答えを選択してください。 – Sma

0

これが最終的な結果である:

bool executed = false; 

void setup() 
{ 
    Serial.begin(115200); 
} 

void loop() 
{ 
    int currentState = digitalRead(D5); 
    if (currentState == 1 && executed == false) 
    { 
     aFunction(); 

     executed = true; 
    } 
    if (currentState == 0 && executed == true) 
    { 
     aFunction(); 
     executed = false; 
    } 

    Serial.println("Still running loop"); 

    delay(2000); 
} 

void aFunction() 
{ 
    Serial.println("in a function"); 
} 
+1

これは、 'D5'が変更されるたびに関数を実行します。これは、元の質問についてのものではないと思います。 – Sma