我的伪代码的本质如下(我将其简化为安排更简单的答案):
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”。
答案 0 :(得分:2)
在循环内,您可以调用break;
以在您调用的循环外继续执行。
答案 1 :(得分:1)
更新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循环