我的伪代码的本质如下(我已经简化它以安排更简单的答案):
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循环)。但是,如果vibrate改变了它的值(即变为零),我希望while循环不被触发,如果它被触发,我想退出while循环。我面临的问题是振动会在while循环之外自行更新,因此我将获得无限循环。有没有更好的方法来加入这个?我也无法在while循环中更新vibrate的值,因为我需要检查更大的'if'。
更新while循环中的vibrate变量。你不需要使用休息
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循环
在循环中你可以调用break;
继续在你调用它的循环之外执行。