Skipher
Skipher

Reputation: 215

Why does the string output from Arduino look like alien text?

I'm trying to set up a serial communication between Arduino and MATLAB over USB. I have this basic code where I'm sending "hello" from MATLAB to Arduino, and I read it back and print it in MATLAB. However, the "hello" sent from Arduino looks like a strange text.

Arduino:

void setup() {
  Serial.begin(57600);
  Serial.println("ready");
}

void loop() {
  String input;
  if (Serial.available()) {
    char c = Serial.read();    
    while (c != '\n') {
      input += c;
      c = Serial.read();
    }
    Serial.println("I received: " + String(input));
    input = "";
  }
}

MATLAB:

s = serial('COM3');
set(s, 'BaudRate', 57600);
fopen(s);
pause(1);

first = strtrim(convertCharsToStrings(fgetl(s)));
if first == "ready"
    fprintf(s, '%s', 'hello\n');
    for i = 1:10
        tline = strtrim(convertCharsToStrings(fgetl(s)));
        disp(tline);
        if size(tline, 2) > 0
            fprintf(s, '%s', 'hello\n');
        end
    end
end

fclose(s);

The output in MATLAB looks like this:

I received: hÿÿÿÿÿÿeÿÿÿÿÿÿÿlÿÿÿÿÿÿÿÿlÿÿÿÿÿÿoÿÿÿÿÿÿÿ

Also, I would appreciate any constructive criticism on improving my code for serial communication. This is my first time, and I'm trying to get a simple setup in which Arduino and MATLAB take turns writing and reading. Thank you.

Upvotes: 0

Views: 221

Answers (1)

Laurenz
Laurenz

Reputation: 1960

Your microcontroller code reads faster than you're physically sending characters, so you're reading from an empty buffer. Serial.available() has one char for you, you read it, then you read more chars even though the receive buffer is already empty. Serial.read() will return -1 when there's nothing to read. -1 cast to char is 0xFF, or in Ascii 'ÿ'.

You could change loop() to something like

void loop() {
  String input;
  while (Serial.available()) {
    char c = Serial.read();    
    if (c != '\n') {
      input += c;
    } else {
      Serial.println("I received: " + String(input));
      input = "";
    }
  }
}

Or you could go with Arduino's Serial.readString():

void setup() {
  Serial.begin(57600);
  Serial.setTimeout(20);
  Serial.println("ready");
}
void loop() {
  String input = Serial.readString();
  Serial.println("I received: " + input);
}

Both untested, but you get the idea.

Upvotes: 2

Related Questions