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)

USEFUL?
We benefit hugely from resources on the web so we decided we should try and give back some of our knowledge and resources to the community by opening up many of our company’s internal notes and libraries through mini sites like this. We hope you find the site helpful.
Please feel free to comment if you can add help to this page or point out issues and solutions you have found, but please note that we do not provide support on this site. If you need help with a problem please use one of the many online forums.

Comments

Your email address will not be published. Required fields are marked *