user794: 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('>', 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?

user794: 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() >= 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('>', data, dataLength);


794: <p>I'm using the <code>Serial1</code> of the Arduino Leonardo to send and receive data with another MCU. The following code will always retrieve garbled data:</p>

<pre><code>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);
</code></pre>

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

<p>What am I missing? Why is the <code>flush()</code> command not working as expected?</p>
 794: <p>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.</p>

<p>To fix this, I had to <code>flush</code> the Arduino serial RX before sending any data. So:</p>

<pre><code>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);
</code></pre>
