clear Serial Buffer

Hello
Today I get stuck on a simple Serial.flush() function since I always presume it was for clear the Serial buffer.
Trying to debug my code that wasn’t working I discover it was the Serial.flush() function.
Going to arduino reference page I found this:

flush() Waits for the transmission of outgoing serial data to complete. (Prior to Arduino 1.0, this instead removed any buffered incoming serial data.)

flush() inherits from the Stream utility class.

Why the hell the function was changed to "Waits for the transmission of outgoing serial data to complete"
How can I delete some bytes on Serial Buffer now?

Why the heal the function was changed to "Waits for the transmission of outgoing serial data to complete"

Some boneheaded decisions can not be explained.

However, the idea of throwing away random amounts of unread data is an idea that hardly deserves having a dedicated function for that purpose. So, bye-bye dedicated function.

If you feel that you must throw away random amounts of unread data, simply loop reading, and discarding, data until there is nothing left to read:

while(Serial.available() > 0)
   Serial.read();

Doing so is NOT advised.

I haven't used the serial for anything other than debugging, however, check the documentation for the return value of Serial.read();

This should hopefully clear the buffer.

while(Serial.read() != -1);

PaulS has a point, maybe the data should be examined.

Well in part yes, but in my case that function was important.Of course I can do that for loop to discard all remain bytes but the code loses some beauty(it was more human readable IMO).
In my project I need to discard some bytes because I have connect several atmega328 on a RS485 BUS and when some incoming data is received I have to check if the message was for him and if not,I need to discard Serial buffer and wait for another stream of data.

PaulS:

Why the heal the function was changed to "Waits for the transmission of outgoing serial data to complete"

Some boneheaded decisions can not be explained.

However, the idea of throwing away random amounts of unread data is an idea that hardly deserves having a dedicated function for that purpose. So, bye-bye dedicated function.

If you feel that you must throw away random amounts of unread data, simply loop reading, and discarding, data until there is nothing left to read:

while(Serial.available() > 0)

Serial.read();




Doing so is NOT advised.

So in it's latest reincarnation, does serial.flush now do something to both the send and rec software buffers, or just the send buffer?

Lefty

In my project I need to discard some bytes because I have connect several atmega328 on a RS485 BUS and when some incoming data is received I have to check if the message was for him and if not,I need to discard Serial buffer and wait for another stream of data.

The underlying assumptions in your statement is that all the data for a packet is in the serial buffer when you flush it, and only one packets worth of data is present.

I don't believe that either one of those assumptions will always be valid.

The only way to know is to read everything in the buffer.

If you are convinced that they both are true, there is no reason why you can't create your own function to throw away random amounts of unread data.

Apart of all this I think the arduino development team should have more careful changing the functions like we are use to work with.
I spend about an hour trying to find what was wrong with my code that was working and now not(after running on the new Arduino version)
So now on I cant trust in older functions because I'm not sure if they are exact as they are in older versions.That a pain ]:smiley: in programming.
It means I had to suspect and test all parts that I consider correct.
Also I don’t see what the name Flush has something to do,on what the function now does.

Waits for the transmission of outgoing serial data to complete

They could just stay the function name alone and implement a new one.More people will lose time if they have Serial.Flush in their code

HugoPT:
In my project I need to discard some bytes because I have connect several atmega328 on a RS485 BUS and when some incoming data is received I have to check if the message was for him and if not,I need to discard Serial buffer and wait for another stream of data.

It is more reasonable to read and discard until some delimiter. Not just whatever happens to be in the buffer, which you don't know what that is, without examining it.

Waits for the transmission of outgoing serial data to complete

It doesn't even do that properly, because it doesn't check for the final byte to be transmitted. You have to augment it with your own check. The original function wasn't particularly useful, nor is the new one.

It doesn't even do that properly, because it doesn't check for the final byte to be transmitted.

If I put a 2ms (depending on baud rate) wait after the flush() would that be a failsafe?

If I put a 2ms (depending on baud rate) wait after the flush() would that be a failsafe?

You only need to do that if you are planning to put the Arduino to sleep, and want to make sure every last byte has left the Arduino before it takes a nap.

PaulS is right, it only really applies before sleeping, or perhaps if you are using some chips like a RS485 interface, and are planning to drop Enable after sending the last byte.

For hardware serial on the Atmega328, this code should do it:

 while (!(UCSR0A & (1 << UDRE0)))  // Wait for empty transmit buffer
     UCSR0A |= 1 << TXC0;  // mark transmission not complete
 while (!(UCSR0A & (1 << TXC0)));   // Wait for the transmission to complete

The 2 mS you suggested depends on the baud rate. At some baud rates it may be too little, at others you are waiting unnecessarily.

I have some sketches which send a request out the serial port (or whatever we call it in Arduino) and then expect a response.

Without a flush, what time frame could be expected for me to be sure that the 2 byte request has been transmitted so that I should go into receive mode? i.e. could the transmission be incomplete 2 seconds after it began?

How does it do this in the background without a multitasking OS? I would have thought that there would be considerable overhead in both sketch size and 'cpu cycles' to handle this in the background. I'm not that fussed either way but I wonder why they went to the trouble of creating this background printing (was it version 1.0?) when there did not seem to be an outcry for it?

Without a flush, what time frame could be expected for me to be sure that the 2 byte request has been transmitted so that I should go into receive mode? i.e. could the transmission be incomplete 2 seconds after it began?

You should expect that serial communication is asynchronous. That is, the device will get back to you not sooner than you talk to it, but any amount of time later.

i.e. could the transmission be incomplete 2 seconds after it began?

It could still be incomplete two weeks later.

How does it do this in the background without a multitasking OS?

How does what do what?

I would have thought that there would be considerable overhead in both sketch size and 'cpu cycles' to handle this in the background.

There is no background to handle stuff in, so there is no overhead involved.

I wonder why they went to the trouble of creating this background printing (was it version 1.0?) when there did not seem to be an outcry for it?

Serial output isn't happening "in the background". It is happening in interrupt service routines.

"I didn't need this; why did they bother?" Well, perhaps someone else did. Having serial output be non-blocking is an improvement. If the Arduino team had not re-purposed a useless function, would you be upset?

lemming:
Without a flush, what time frame could be expected for me to be sure that the 2 byte request has been transmitted so that I should go into receive mode? i.e. could the transmission be incomplete 2 seconds after it began?

I agree with everything PaulS said. Plus you may want to read this:

I would have thought that there would be considerable overhead in both sketch size and 'cpu cycles' to handle this in the background.

No, it is the nature of these sort of processors (all processors really) that some stuff should be promptly handled by interrupt service routines. They are cunningly designed to be short and quick.

lemming:
I have some sketches which send a request out the serial port (or whatever we call it in Arduino) and then expect a response.

That's fine. When the response comes in not in your control nor to worry about, you just keep checking with the serial.available command and it will tell you how many characters if any it has seen and stored away in a memory buffer. Don't check serial.available quick enough or often enough you can indeed lose characters as the ring buffer overwrites the oldest received characters to store newer arriving ones. When serial.avalible tells you there are characters available you just perform serial.read commands and do what you wish with them.

Without a flush, what time frame could be expected for me to be sure that the 2 byte request has been transmitted so that I should go into receive mode? i.e. could the transmission be incomplete 2 seconds after it began?

You never have to issue a flush command, it really is a very obscure command with no real useful function except perhaps as stated already to prepare the chip for sleep mode. you don't go 'into receive mode', incoming characters will automatically be placed into a memory buffer and testing with serial.available is all you have to do to keep up with the response whenever that might be.

How does it do this in the background without a multitasking OS? I would have thought that there would be considerable overhead in both sketch size and 'cpu cycles' to handle this in the background. I'm not that fussed either way but I wonder why they went to the trouble of creating this background printing (was it version 1.0?) when there did not seem to be an outcry for it?

The serial library uses fully buffered interrupt driven functions to store incoming and send out going serial characters. It's all transparent to the user and you only have to keep up with the incoming data stream by testing the serial.avalible command often enough. You can think of the built in serial interrupt functions as working 'in the background' if it suits you, but I think you are making the whole concept harder then it really is. Just send data when you have characters to send and keep polling the serial.available command to see if any and if so how many characters are ready for you to read.

Lefty

"I didn't need this; why did they bother?"

As I mentioned, I'm not fussed by it but I was curious why they went to the effort when they have enough on their plate to do without taking this feature. I had not seen any demand for it in the forums (although I may have missed it) and thought that they would be busy with other, more in demand, features. I'm not saying that because I don't use it, no-one else should have it.

How does what do what?

Print without blocking.

Serial output isn't happening "in the background".

I'm still not clear on how it works.... If its not blocking execution of the code after the print statement and carries on execution of the subsequent code while still completing the print statement at a later time then that would seem like a background task. Just like on single processor PCs, where multitasking is not really concurrent multitasking but just faking it with time slicing very quickly.

It could still be incomplete two weeks later.

Does this mean that we should always use a flush after a print statment?

EDIT:
Cross post. Lefty answered most of this while I was writing.

Does this mean that we should always use a flush after a print statment?

Serial.print("switch state: ");
Serial.println(state);

Do I really need to block waiting for this data to get to the Serial Monitor?

Do I really need to block waiting for this data to get to the Serial Monitor?

You may if that message may not be printed for some time.

It could still be incomplete two weeks later.

In my polling sketches I do not want to waste time hanging around for response strings when the request has not been completely sent.
I want to send the request, make sure its gone, and wait for the reply knowing that it is going to come back soon so I can get on with other tasks.

lemming:
I do not want to waste time hanging around for response strings when the request has not been completely sent.

You should not be wasting time hanging around for response strings after the request has been sent, either. If you design your sketch correctly it will handle response strings as and when they arrive, and continue dealing with anything else that needs doing in the meantime.

Thanks PeterH but the "anything else that needs doing in the meantime" is sending requests to other nodes which also may or may not respond in a timely manner due to this issue. Therefore the next reply coming back may be for the most recent request or one from some time ago. I thought of using a stack to keep track, but sometimes a response will not come back (the device connected to the serial port is a radio). One may send out four requests and only get three responses. Which goes with which? I can use header records with IDs but it would be simpler to send a request and know that the ensuing response was for the just-made request: or the absence indicates a problem which can be dealt with there and then.