Sending serial data to Arduino - Arduino receives extra mysterious characters

I've dutifully spent a couple of hours trying to crack this problem / search for answers, but I'm still stuck and confused.

I am sending serial data to an Arduino Mega from the Arduino IDE. If I send "test", The arduino shows that it receives "t⸮⸮⸮e⸮⸮s⸮⸮⸮t⸮⸮⸮⸮⸮"

However, if I add a 100 millisecond delay in the loop receiving the serial data, the strange "⸮" goes away.
While I could fix the problem by adding a slight delay, I would like to understand why I am getting mysterious data so that I can fix the problem properly.

If I don't interpret them as characters, the "⸮" is equal to "-1"

String message = "";
int myArray[40];
int arrayCount = 0;

void setup() {
  Serial.begin(115200); // I chose 115200, but I am having the problem with other speeds also
  Serial1.begin(9600);
}

void loop() {
  message = ""; // variable for composed message
  if(Serial.available()){
    while(true) { // run loop until "/n" is found and the loop is broken
      //char myChar = (char)Serial.read();
      char myChar = Serial.read();

      myArray[arrayCount]=myChar;
      arrayCount ++;

      Serial.flush(); // not sure if this helps, but it is one of the recommendations I found on a forum
      // A deley removes the extra characters 
      //delayMicroseconds(100);
      if (myChar == '\n'){
        break;
      }
        message += myChar;
    }
      // Show composted message recived
      Serial.print("recived message: ");
      Serial.println(message);

      // Show individual characters. 
      //for(int t=0; t<arrayCount;t++){
        //Serial.println(myArray[t]);
      //}
  }
  
}

Thank you for any insight!

You check whether serial data is available, which could mean as little as 1 byte, then read from serial without checking whether any more serial data has arrived. If no serial data is available then Serial.read() returns -1

You need to read from serial only if something is available

See Serial input basics - updated

@OP

Upload the following simple sketch (tested on MEGA) created based on the directives of Post#1. If you are happy with the response of the sketch, then add other features with the sketch as your mind says.

void setup()
{
  Serial.begin(115200); // I chose 115200, but I am having the problem with other speeds also
  //Serial1.begin(9600);
}

void loop()
{
  byte n = Serial.available();
  if (n != 0)
  {
    char x = Serial.read();
    Serial.print(x);
  }
}

sm-5.png

sm-5.png

Thank you for helping me understand what is happening :slight_smile:

Your code worked like a charm!