我需要我的代码在循环中停止,我试图中断但方法 sendToGCM() 继续。我只想让方法执行一次,stop while condition
void loop()
{
// Other code here giving temp a value
if (temp > 22)
{
status = false;
value["status"] = status;
while (temp > 22)
{
sendToGCM(); // Sends push notification
break;
}
}
else
{
status = true;
value["status"] = status;
}
}
最佳答案
因此,如果我没理解错的话,如果温度达到 22 度,您想要发送消息,但只是第一次。如果你打破循环,如果你再次执行 loop()
函数,你仍然会进入它。
为了实现你想做的事情,你的代码需要看起来像这样
boolean message_sent;
void loop() {
...
if(temperature > 22 && !message_sent) {
sendToGCM();
message_sent = true;
}
}
如果你想在每次温度上升超过 22 度时发送一条消息,你需要这样的东西
boolean message_sent;
boolean was_under_22;
void setup() {
...
was_under_22 = function_that_checks_if_temp_is_under_22();
...
}
void loop() {
...
if(temperature > 22 && was_under_22) {
if(!message_sent) {
sendToGCM();
message_sent = true;
was_under_22 = false;
}
} else {
was_under_22 = true;
message_sent = false;
}
}
编辑:根据 Patrick Trentin 的评论稍微调整了代码。该代码假定您只想在温度上升到 22 度以上时捕获,并且如果 Arduino 开始时温度超过 22 度,则不会发送任何消息。
关于c++ - 当条件激活时停止 arduino 循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41858929/