Serial.flush()?

Hello! I am very new to Arduino so bear with me! :slight_smile:

After reading previous forum topics and the page for Serial.flush(), I still do not understand how to implement it in my code. Is it really necessary? I currently have one Bluetooth module (RN42) attached to ports 19 and 18 (TX1 and RX1) and another Bluetooth module attached to ports 17 and 16 (TX2 and RX2) on the Arduino Mega board. Below is the current code that I am using.

char datafromBT; 

  if (Serial1.available() > 0) {  
    datafromBT = Serial1.read();  
    Serial2.write(datafromBT);
    Serial2.flush();

My question is, is the Serial.flush() necessary for the code and if it is, is it correctly placed? I have another Arduino Mega which uses another Bluetooth module and it will receive the data from Serial2's Bluetooth module.

Many thanks for your help! :slight_smile:

The only purpose of Serial.flush() is to make your program wait until all the data in the Serial Output Buffer has been sent.

It is rarely necessary.

...R

Robin2:
The only purpose of Serial.flush() is to make your program wait until all the data in the Serial Output Buffer has been sent.

It is rarely necessary.

...R

So, I do not have to add Serial2.flush() if I’m sending data from Serial1 to Serial2, since it’s not necessary?

narzonmars:
So, I do not have to add Serial2.flush() if I’m sending data from Serial1 to Serial2, since it’s not necessary?

Have you tried leaving it out?

What happened?

The Arduino system is great for learning-by-doing.

However why anyone would send data from Serial1 to Serial2 beats me.

...R

I'm sending the data from Serial1 to Serial2 just for research purposes.

And I did try putting in the Serial.flush() but it seemed to be the same result when I don't put it in. So, what really is the point of Serial.flush() when it will return me the same result? ???

The Arduino developers thought that someone might need Serial.flush() on some occasion.

Probably after the serial2.flush you could send back an acknowledge on serial1 which should have a remote that is waiting for the acknowledge. That way serial1 does not sink into a swamp while serial2 is flushing.