How can I call an if statement in a loop() once until another condition is met

I have in my loop function something like this:

void loop() 
{  
  //Calculate the current of sensors  
  double Irms1 = emon1.calcIrms(1480);
  double Irms2 = emon2.calcIrms(1480);
  double Irms3 = emon3.calcIrms(1480);

  //Show current in display
  
  lcd.setBacklight(HIGH);
  lcd.clear();
  lcd.setCursor(0,0);
  lcd.print("Lav:1   2    3");
  lcd.setCursor(1,1);
  lcd.print(Irms1);
  lcd.setCursor(7,1);
  lcd.print(Irms2);
  lcd.setCursor(12,1);
  lcd.print(Irms3);


  //Post the current in some API
  if(Irms1>1.00) {
    postData(1, 1); //first parameter is id, second is the state (0 = turned off, 1= turned on)
  } 
  if(Irms2>1.00){
    postData(2, 1);
  }
  if(Irms3>1.00){
    postData(3, 1);
  }

}

The Problem is, when the arduino reads the currents, if the condition is met it always post the state turned on until it is turned off, what I needed to do is when it reads the current and it is turned on (Irms>1.00), then it should post the state turned on once, and update this state just only when the state changes to turned off (Irms<1.00).

I’ve tried to put this out of loop, but I need to constantly read the currents to see if the sensor reads another state.

What could I do to solve this?

What could I do to solve this?

Use a boolean.

bool beenThereDoneThat = false;
  if(Irms1>1.00)
  { // Down here, where it belongs
    if(!beenThereDoneThat)
    {
       postData(1, 1);
       beenThereDoneThat = true;
    }
  }
  else
    beenThereDoneThat = false;

Add a Boolean variable that will remember when you posted the information already and test that one before posting again.

Thank you!

I’ve worked this by creating the boolean variable and my code ended up like this:

if ((Irms1>1.00) && ((!turned_on))) {
    postData(1, 1);
    turned_on = true;
  } else if ((Irms1<1.00) && ((turned_on))) {
    postData(1, 0);
    turned_on = false;
  }
[code]

I hope this can help someone with similar problems.

[/code]

Slight suggestion:

Remember that in C or C++ a boolean && operation will stop evaluating as soon as it finds a false (because false && whatever is false).

So for performance (here does not matter much) In the order of the tests in your if, It's usually better to test your boolean first as it is likely to be the value that most often dictate whether or not it's even worth evaluating Irms