Clearing the serial port's buffer Clearing the serial port's buffer linux linux

Clearing the serial port's buffer


I think I figured it out. For some reason, I need to add a delay before flushing. These two lines added before returning fd seem to have done the trick:

  sleep(2); //required to make flush work, for some reason  tcflush(fd,TCIOFLUSH);


I have been experiencing similar symptoms with an Arduino Uno board that resets on open(). I was receiving data after the open() call that was generated before the Arduino board had been reset and thus before open() had been called.

Tracking down the issue with ioctl() calls I learned that the data had simply not yet arrived in the input buffer by the time tcflush() was called. So the tcflush() did work but there was no data to flush. A sleep of 1000 us after the open() call seemed to solve the issue. This is becasue the delay allowed the data to arrive before tcflush() was called and therefore tcflush() did indeed flush the input buffer.

You might be experiencing the same issue.


The cause of this problem lies in using a USB serial port. If you use a regular serial port, you will not have this problem.

Most USB serial port drivers don't support flushing properly, probably because there's no way of knowing if there's still data in the internal shift register, FIFO or in the USB subsystem.

See also Greg's reply to a similar problem reported earlier here.

Your sleep may cure the problem, but it's only a work-around. Unfortunately there is no solution other than using a regular serial port.