如何在传感 if 条件下打破 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 循环