Waiting for TX to complete – Flush
When you issue a Serial.print() or Serial.write() , the function returns almost immediately. Instead of waiting until the string or data has been transmitted, it sets up a buffer for the data which is then transmitted via interrupts one byte at a time. I.e., your program keeps running, with the transmitting of bytes happening in the background.
Serial.flush()
Using this in your code:
Serial.flush();
https://www.arduino.cc/en/Serial/Flush
Causes program execution to wait for the transmission of outgoing serial data to complete. Execution is stalled.
NOTE – this does not mean the byte has actually been transmitted!
It just means the byte has been passed to the microcontroller TX register and is being transmitted.
In our tests with a Mega2560 we also found it did not necessarily always return straight away, sometimes we saw long delays before it returned.
Waiting for TX to complete – Using Microcontroller Registers
Wait for the TX of a byte to complete using TXCn (USART Transmit Complete) bit
Arduino Mega2560
while (!(UCSR3A & 0x40)) //Bit6 = TXCn: USART Transmit Complete
;
Use UCSR0A, UCSR1A, UCSR2A, UCSR3A depending on serial port (Serial – Serial3)