簡體   English   中英

如何打破感測是否條件內的while循環

[英]How To Break a while loop inside a sensing if condition

我的偽代碼的本質如下(我已對其簡化以安排更簡單的答案):

if (vibrate == 1){ //this is the input sensing to the arduino. 
  //It is either 1 or 0
  //constantly run a while loop IF vibrate ==1
  i=51;
  while(vibrate ==1){
     analogWrite(Motor,i); //constantly outputing a pulse of increasing magnitude
     delay(10); //delay it for a certain period of time
     i=i+50; //increment i 
     if (i>=255){
       i=51;
     }
  }
}
else{ //do something else. Has it's own functions}

現在,振動從傳感器進入。 如果振動為1,我將自動希望輸出一個斜坡脈沖(即while循環)。 但是,如果振動改變了它的值(即變為零),我希望不觸發while循環,如果它被觸發,我想退出while循環。 我面臨的問題是,振動會在while循環之外進行自我更新,因此我將得到一個無限循環。 有沒有更好的方法來合並這個? 我也無法在while循環中更新振動值,因為我也需要檢查更大的“ if”。

在循環中,您可以調用break; 在您調用的循環之外繼續執行。

在while循環中更新振動變量 您不需要使用break

void updateVibrate(){
       //UPDATE THE VIBRATE VARIABLE
    }

    if (vibrate == 1){ //this is the input sensing to the arduino. 
      //It is either 1 or 0
      //constantly run a while loop IF vibrate ==1
      i=51;
      while(vibrate ==1){
         analogWrite(Motor,i); //constantly outputing a pulse of increasing magnitude
         delay(10); //delay it for a certain period of time
         i=i+50; //increment i 
         if (i>=255){
           i=51;
         }
       updateVibrate();//Call function which will update the vibrate (Global) Variable
      }
    }
    else{ //do something else. Has it's own functions}

另外,當迭代次數固定時,可以使用帶有break語句的for循環

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM