Serial.read has garbled data after a Serial.write I'm using the Serial1 of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:

byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('&gt;', data, dataLength);


But, if I add a delay(50) before the Serial1 read, I would get the expected output. The value 50 was found by trial and error.

What am I missing? Why is the flush() command not working as expected?
I've finally found that when the MCU  to which Arduino is talking to was initialized, it would send spurious data to the Serial - I guess it would start first with a lower baud rate, and then switch to the programmed baud rate of 115200.

To fix this, I had to flush the Arduino serial RX before sending any data. So:

byte streamReadResponse;
Serial1.begin(115200);
Serial1.setTimeout(9000);
while (Serial1.read() &gt;= 0)
           ; // do nothing
Serial1.print(cmd);
Serial1.print('\r');
Serial1.flush();  //wait for all the data to be sent to the serial
streamReadResponse = Serial1.readBytesUntil('&gt;', data, dataLength);