Understanding the relation between Serial.available() and Serial.Read() Function

(This is a copy of my post of this link. Moderator may kindly delete this thread if found redundant.)

In good old days of DOS/C/UART Programming, we first executed a line of code to check that a character has really arrived at the receiver section of the serial port and then we executed another line of code to read the arrived data byte from the receiver section. This was to avoid the wastage of time as it was useless to make an attempt to read a data byte from the receiver section when there is no character that has arrived.

In Arduino Serial Platform, the Serial.available() and the Serial.read() function exactly do the above two tasks at Conceptual Level.

In addition, the Arduino has incorporated an unseen 64-byte wide FIFO buffer to accommodate charcaters as they arrive (provided the characters are not read when they have arrived). The buffer, in fact, can store 63 characters as the last byte is a null-byte. As the FIFO buffer is not directly accessible by the user, the program must execute the Serial.read() instruction to bring the content of the FIFO buffer into the user defined variable.

The following program shows that the buffer keeps accommodating 5 unread charcaters (say, a b c d e) as they are entered one at a time from the InputBox of the Serial Monitor (No line ending option should be active); at the end of the reception of 5 characters, the Serial Monitor shows abcde in the OutputBox of the Serial Monitor.

char myData[20] = "";

void setup()
{
  Serial.begin(9600);
}

void loop()
{
  if (Serial.available() > 0)
  {
    byte n = Serial.available();
    if ( n == 5)
    {
      for (int i = 0; i < n; i++)
      {
        myData[i] = Serial.read();
      }
      Serial.println(myData);
    }
  }
}