Problem on multiple use of serial.available() in single void loop()

First you will need to make sure that the serial monitor line endings are set to None.


Or add a trim function to trim the invisible carriage return and/or line feed from the serial input.

str = Serial.readString(); //save the incoming data in the string
str.trim(); // trim invisible white space characters

If there is nothing available in the second

 if (Serial.available())

"Test" would have to be entered again to get to that part of the program.

You could use while(Serial.available() == 0); to wait for serial input. Not the best way to do it though.

The code looks like this:

int newval = 0;// initialize newval and str
String str = "";
void setup()
{
   // put your setup code here, to run once:
   Serial.begin(9600);

}

void loop()   // put your main code here, to run repeatedly:
{
   if (Serial.available()) //check if there is any data
   {
      str = Serial.readString(); //save the incoming data in the string
      str.trim(); // trim off invisible characters

      if (str == "Test")  //check if
      {
         Serial.println("This is the first response");
      }
      if (str == "Test2")// check if Test2
      {
         Serial.println("Input some number.");

         while (Serial.available()== 0); // wait for the second incoming data and print accordingly, however it does not go thru the code.
         {
            //newval = 4;
            newval = Serial.read();
            Serial.println(char(newval));  // char converts ASCII code to character
         }
      }
   }
}

That is not the best way to wait for serial input. If you do a search for "arduino wait for user serial input", you should get some better ways.

You should try to stay away from using the String class. The, easily misused, String class can cause memory problems. See the evils of Strings page.

Robin2's serial input basics tutorial shows robust ways to read serial data into strings (null terminated character arrays).