Joseph Jay May
Joseph Jay May

Reputation: 13

Stop arduino loop when a condition is active

I need my code to stop in the loop, i have tried to put in a break but the method sendToGCM() continues. I only want the method to be executed once, the stop while the 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;
  }
}

Upvotes: 0

Views: 1391

Answers (2)

wastl
wastl

Reputation: 2641

So if I understood you correctly, if the temperature goes 22 degrees you want to send a message, but only the first time. If you break the loop, you still enter it if you the loop() function is executed again.

In order to achieve what you want to do, you code will need to look something like this

boolean message_sent;

void loop() {
    ...
    if(temperature > 22 && !message_sent) {
        sendToGCM();
        message_sent = true;            
    }
}

If you want to send a message every time the temperature rises over 22 degrees you would need something like this

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;
    }
}

EDIT: slightly adapted the code in response to Patrick Trentin's comment. The code assumes you only want to capture if the temperature rises above 22 degrees and that if the Arduino starts with over 22 degrees then no message is sent.

Upvotes: 2

Trevor
Trevor

Reputation: 366

Your problem is that you are setting temp, then entering the loop that checks that value. A simple solution would be to update the temp value inside the while loop, to give the application a chance to break out of the while loop.

Example:

void loop()
{

  // Other code here giving temp a value

  if (temp > 22)
  {
    status = false;
    value["status"] = status;
    while (temp > 22)
    {
      sendToGCM(); // Sends push notification 

      //Additional code to set the value of temp, allowing the value to
      //be greater than 22.
    }
  }
  else 
  {
    status = true;
    value["status"] = status;
  }
}

Please note that the above example is intended to continuously send the push notification while the temp value is over 22. If that's not the intention, just remove the sendToGCM() from the while loop. You will still only send it if the temp is greater than 22, since you have the if check.

Upvotes: 0

Related Questions