Unexpected serial data

On the serial monitor when I print out the serial data sometimes it will randomly split the input with new lines. For example if I type "move", sometimes it will print "m" then add a newline then "ove", and sometimes it just prints "move" on the same line.

  • void setup() {
  • Serial.begin(9600);
  • }
  • void loop() {
  • String Q;
  • String readString = "";
  • while(Serial.available()){
  • delay(1);
  • if(Serial.available()>0){
  • char c = Serial.read();
  • if (isControl(c)){
  • break;
  • }
  • readString+= c;
  • }
  • }
  • if(readString!="")
  • {
  • Q = readString;
  • Serial.println(Q);
  • readString = "";
  • }
  • }

This is your sketch between code-tags:

void setup()

void loop()
  String Q;
  String readString = "";

  while (Serial.available())
    if (Serial.available() > 0)
      char c = Serial.read();
      if (isControl(c))
      readString += c;

  if (readString != "")
    Q = readString;
    readString = "";

The loop() is executed over and over again, it could be thousands of times per second. Each time the loop() runs, the 'String Q' and 'String readString' are created as brand new variables.

Your 9600 baud is slow and the delay(1) might help to get another byte. You do the Serial.println() yourself without knowing if you have received a full line (you probably did not).

You can do delay(10) to get more bytes. But that is just guessing, that is still not reliable. It would be better if you don't need any delay and always read a full line.

You have to think about the protocol of the serial data. What kind of data is it ? It there a CarriageReturn or LineFeed or both or none at the end ? Do you want a timeout ? How do you keep the sender and receiver in sync.

Hello abojiuc,
I suggest you follow this excellent tutorial on using serial

Thanks everyone for your replies.
The tutorial was really helpful. I'm gonna play around with the code see if I can get it to work using your suggestions.