Bluetooth serial- a condition in the condition

hi, I need to make a program where I have buttons in the app on my phone and send them via HC-05 Bluetooth serial to Arduino. In Arduino, I have to make a condition in the condition. Example:

if(Serial.readString()=="Button1")
{
     if(Serial.readString()=="Button3")
     {

     }
      else if(Serial.readString()=="Button4")
     {

     }
}
else if(Serial.readString()=="Button2")
{
     if(Serial.readString()=="Button5")
     {

     }
} 

It is usual to read the string from Serial into a String, and then compare that repeatedly.

Hard to tell what you want to do, given the lack of comments and a specification.

and the problem is that when I load "Button1" and then I want to press "Button3" 3 times in a row, it doesn't go through the first condition if (Serial.readString () == "Button1"), and I want, that it will be staying in (Serial.readString () == "Button1") condition unless I press button 2, the others will not be affected

first comment is that you don't want to read many times. Just once because once you've read it, it's gone from the Serial buffer.

String message = Serial.readString();
if (message == "Button1") {

} else if (message == "Button2") {

}

what it seems is that if you get Button1 then the next actions can only be Button3 or Button4

➜ you need some sort of state machine to handle this or your code will very quickly become spaghetti code :slight_smile:

the other thing is that readString() will play tricks on you with timeout etc... I would suggest to study Serial Input Basics to understand how to listen to the Serial port

...line endings...

that too !

here is an example of a small state machine:

enum : byte {waitingForB1orB2, gotB1, gotB2} state = waitingForB1orB2;

String message = "";

bool newMessageAvailable() {
  bool messageReceived = false;
  // ... <=== to write
  return messageReceived;
}

void handleBT() {
  if (newMessageAvailable()) {
    switch (state) {
      case waitingForB1orB2:
        if (message == "B1") {
          state = gotB1;
        } else if (message == "B2") {
          state = gotB2;
        }
        break;
      case gotB1:
        if (message == "B3") {
          // handle sequence B1/B3
        } else if (message == "B4") {
          // handle sequence B1/B4
        }
        state = waitingForB1orB2;
        break;
      case gotB2:
        if (message == "B5") {
          // handle sequence B2/B5
        }
        state = waitingForB1orB2;
        break;
      default: break; // error
    }
  }
}

void setup() {
  Serial.begin(9600);
  message.reserve(20);
}

void loop() {
  handleBT();
}

you "just" have to write the function newMessageAvailable() :slight_smile: