0

I am using an Arduino M0 Pro and have a device connected via Pin 0 and 1 of it. So I am using the predefined Serial5 interface to receive data from it. I have the following code snippet/method that tries to read an answer from Serial5 if it is available. Otherwise it returns an empty string.

String read_answer() {
  String str = "";
  // Check if bytes are available
  if (Serial5.available()) {
    char c;
    // Read an character unless the read() method returns -1
    // The -1 is identical to 255
    while ((c = Serial5.read()) != 255) {
      // Append the read character to the string array
      str.concat(c);
    }

    // Output the string on the serial debug interface
    Serial.print("Read: \"");
    Serial.print(str);
    Serial.print("\"\n");
  }
  // Return the read string
  return str;
}

If I send an the following string "ABCDEF HIJKL MNOPQR" via an FTDI towards it the first times it correctly printed :

Read: "ABCDEF HIJKL MNOPQR"

But suddenly it just stops reading the complete string. The output is something like that:

Read: "ABCDEF HIJKL MN

It is just cut off and everything stops working, over and over again. It might be a very stupid mistake but I don't know where to check next. If I missed something to explain or more context is needed pls tell me.

1

Your code has no idea when the string is finished. At the moment it is just waiting until the receive buffer is empty (Serial.read() returns -1), but since serial is a slow protocol that could happen at any time, not just at the end of the string.

You need something to terminate your string so it knows when the end is. The most common way is to use a line feed character (\n, character 10) or a carriage return (\r, character 13) or a combination of the two.

char c;
while ((c = Serial5.read()) != '\n') {
    if (c != 255) {
        str.concat(c);
    }
}

// Output the string on the serial debug interface
Serial.print("Read: \"");
Serial.print(str);
Serial.print("\"\n");
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.