c++ - 当条件激活时停止 arduino 循环

标签 c++ if-statement while-loop arduino break

我需要我的代码在循环中停止,我试图中断但方法 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/

相关文章:

c++ - 使用 sgbm 的视差图

c++ - 常量成员函数可变

c++ - 转换为 union 和奇怪的数字格式

Python 不能根据两个整数的值给字符串赋值

MySQL 使用 IF 语句

bash - 在 Bash 中使用多个表达式复合 'if' 语句

java - 是否可以在 while 循环中简洁地使用复杂的条件?

C++ 将子子类转换为基类

php - While 循环显示不同行而不是同一行

java - 试图用开关盒内的开关盒打破 while 循环