【发布时间】:2016-07-02 14:09:23
【问题描述】:
我正在使用 Arduino 进行编程,我的程序包含很多 while 循环。当 Arduino 接收到一个字符时,它必须进行一些计算并打破它在接收到一个字符时所处的循环。我给你举个更简单的例子(假设 i 和 j 都设置为 0):
while (i < 256)
{
// some calculations #1
i++;
if (Serial.available() > 0)
{
setStringOne = "string one"
setStringTwo = "string two"
setStringThree = "string three"
setStringFour = "string four"
break;
}
}
while (j < 256)
{
// some calculations #2
j++;
if (Serial.available() > 0)
{
setStringOne = "string one"
setStringTwo = "string two"
setStringThree = "string three"
setStringFour = "string four"
break;
}
}
您可以看到,在这两种情况下,我在 if 语句中都使用了相同的代码。我希望它能够写出这样的东西。
while (i < 256)
{
// some calculations #1
i++;
if (Serial.available() > 0)
checkAndBreak();
}
while (j < 256)
{
// some calculations #2
j++;
if (Serial.available() > 0)
checkAndBreak();
}
void checkAndBreak()
{
if (Serial.available() > 0)
{
setStringOne = "string one"
setStringTwo = "string two"
setStringThree = "string three"
setStringFour = "string four"
break;
}
}
使用外部方法中断循环。
它给了我一个错误“break statement not within loop or switch”,这是意料之中的,因为它不知道要从哪个循环中断,但我只是想知道是否有可能按照这些思路进行操作。
提前致谢!
【问题讨论】:
-
您可以使用
checkAndBreak宏或异常或longjmp。 -
将循环条件更改为
while (j < 256 && Serial.available() <= 0 )应该可以让您摆脱中断 -
哦,我还没想过。谢谢。
-
你考虑过使用异常吗?
-
我从未在 Arduino 上处理过异常,所以我真的不知道如何实现它们。