Error serial read from arduino nano

Hi I am using pixhawk hardware(M4 microcontroller ), Arducopter software inside, connected with Arduino nano with serial communication. The Arducopter uart is originally from arduino library. So the serial API has read(), avaiable(), write() and so on API. Here is the github.
First I send a string like #360;500*, 360 means angle and 500 means range, both of them are changing. Then send through Serial.println. The buadrate is 57600 and it takes 5ms to send this data format. In my macbook, the serial monitor output always right. But in the pixhawk, the data receive randomly fine and wrong. I use the code below to receive data, sometimes it's fine, but sometimes it likes:#100;233*, #102;233*,#104;233*..The range data get always same.

int r = hal.uartE->read();
if (r != '\n'){
            char s[2];
            sprintf(s, "%c", r);
            strcat(m_dataBuf, s);
}
else{
            hal.console->printf("data:%s\n",m_dataBuf);
            m_dataBuf[0] = '\0';
}

Then I think maybe string take too much cost and use

Serial.write

to send highbyte and lowbyte to pixahwk. But the result always same.

I know maybe some of you don't familiar pixhawk and Arducopter, but the serial from arduino, ant it's a microcontroller. maybe you can give me some suggestions will the problems is. Is that a receive buffer size problem?

Using strcat instead of holding on to a count is very inefficient. strcat has to start at m_msgbuf[0] and search for the NUL terminator. This means that accumulating n characters takes on the order of n2 operations. For 13 characters, this is actually 91 array index and comparison operations, plus an additional 12 assignments for the NUL terminator.

Instead, hold on to a count and NUL-terminate m_dataBuf when you receive the '\n'. See Serial Input Basics and Nick's How To....

This also avoids the expensive sprintf. :stuck_out_tongue:

if (hal.uartE->available()) { <-- I *assume* you have this somewhere above!

  char c = hal.uartE->read();
  if (c != '\n'){

    if (count < sizeof(m_dataBuf)-1) {
      m_dataBuf[ count++ ] = c;
    }

  } else{
    m_dataBuf[ count ] = '\0';
    hal.console->print( F("data:") );
    hal.console->print( m_dataBuf );
    count = 0;
  }

Actually, echoing the data back is probably the major problem. You are trying to print 5 more characters than you received: the "data:" characters take time, too. If the Arduino is sending the data as fast as it can, 15 bytes per command, the above print will eventually block because it is sending 20 bytes per command. While it's waiting to print, the input buffer overflows, which causes it to lose random characters.

Cheers,
/dev

thx, I found my issues which is leaded by my arduino code not serial problem. But still appreciated your help to make me understand more about serial communication.

But not post that code here so everybody (including you) can learn?