Reading strings on serial monitor inserts backwards question marks between chars

Hi everyone. I am having issues reading strings from the serial monitor. Right now I have a function that is supposed to just read characters and add them to a string until a \n appears and then return the string. It will read the string fine but it inserts backwards question marks between each character of the string.

Here is my code

String serial_get(){
  String str="";
  char inchar = NULL;
  if (Serial.available() > 0) {
    while (inchar != '\n') {
      if (Serial.available()>0);
        inchar=Serial.read();
        str += inchar;
    }
  }
  return str;
}

void setup() {
  // put your setup code here, to run once:
  Serial.begin(38400);
}

String s = "";
void loop() {
  // put your main code here, to run repeatedly:
  s = serial_get();  
  if (s!="") {
    Serial.println(s);
  }
  s="";
}

here exactly what I put in the input

1234

This is what I expected to come out (includes '\n' from line ending)

1234

Actual result

1⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮2⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮3⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮4⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮⸮

I added the if statement to ensure I wasn't trying to read from the serial port if nothing was there. I don't understand the issue...

Thanks for any help :slight_smile:

Jacob

Serial is really, really slow.

Think about your while loop.

Also if (Serial.available()>0); Why the semicolon?

:o Thank you so much. Definitely should have caught that...

     if (Serial.available() > 0);
      inchar = Serial.read();
      str += inchar;

The semi colon on the end of the if should not be there and I assume that if Serial.available() is greater than 0 then the next 2 lines should be executed and not just the first one.

Remove the semi colon and put {} round the dependent code block

      if (Serial.available() > 0)
      {
        inchar = Serial.read();
        str += inchar;
      }

Thanks. I have it sorted out now.

...and try your best not to use String if you're using an eight bit Arduino.