Flushing arduino serial output buffer?

How do I flush output buffer? I need data from arduino forwarded to C program and I want the data to wait until I want to read the data. If the program runs for hours I wont want to read 10K characters and analyze it until I come to string I want. So I tried: Serial.print("one"); Serial.flush(); Serial.print("two");

But and my C program reads later "onetwo" but I want only last output to be read, so only "two" How do I flush this buffer? Is that possible?


Do I understand correctly?

You want your Arduino to repeatedly generate data, but you only want the most recently captured data to be transmitted when the host computer needs it? If this is correct, then why not write the Arduino code so that it transmits only in response to a request from the C program running on the other end of the wire?

//Arduino code
void loop()
  if (Serial.available())
    int c = Serial.read();
    if (c == '?')
      Serial.print(... some data ...);

On the C side, you would simply transmit a '?' character whenever you want some data.

In your example code, flush is not a synonym for "clear". Once you have Serial.printed "one", it's gone.


flush usually denotes the flushing of an output buffer to the device (e.g. fflush()), i.e. to force all buffered data to be written.

The solutions that seem obvious to me are to either write the data on demand, as Mikal suggests, or to rewrite your receiving program so that it discards data until you are ready for it.


As was pointed out in another forum, the arduino serial output code does not have any output buffer. Just the two bytes worth of shift register and transmit holding register in the uart itself.

OK, I understand, I thought it keeps sending the same data until you flush it. Thanks for the explanations. I will use Mikal's method!