Clearing RX Serial Buffer

Hi!
I would like to write a function which clears my RX buffer. And I know the most obvious answer:

void ClearBuffer(){
  while(Serial.available()){
    Serial.read();
  }
}

But in my application, I have to do this MUCH faster than just reading all data. Arduino hardware serial uses RX ring/circular buffer - so I would like to simply override buffer head address with buffer tails address . If im thinking right, this would be the fastest way of clearing rx buffer, but I cant really find any information about those tail/head addresses. Any advices on that?

Gosucherry:
But in my application, I have to do this MUCH faster than just reading all data.

What you have posted is how I would do it.

How long do you think that piece of code takes to complete?

How quickly (in microseconds) do you need to clear the buffer?

...R

you could patch the HardwareSerial.h /.cpp to add a function

void HardwareSerial::clearRXBuffer()
{
_rx_buffer_head = _rx_buffer_tail;
}

faster than that is diificult.

A non-core patch version could be

void clearRXBuffer()
{
  int x;
  while (x = Serial.available() > 0)
  {
     while (x--) Serial.read();
  }
}

the advantage is that available() is called far less so should be (max 2x) faster.

Robin2:
What you have posted is how I would do it.

How long do you think that piece of code takes to complete?

How quickly (in microseconds) do you need to clear the buffer?

...R

My application is based on very precise time windows, which are set to 500uS. Since I was having a 40 bytes in RX buffer I had to waste lot of time discarding it ( over 300uS ). Why do I have stuff in RX buffer that I dont want to read? Its because I'm making multiple nodes ( Arduino Unos ) talking over MAX485 in order :slight_smile:

robtillaart:
void HardwareSerial::clearRXBuffer()
{
_rx_buffer_head = _rx_buffer_tail;
}

This is the very thing I was looking for! Thank you. It takes ~8uS :slight_smile:

Created an issue for this improvement - Add flushReceiveBuffer() to HardwareSerial · Issue #89 · arduino/ArduinoCore-API · GitHub

robtillaart:
you could patch the HardwareSerial.h /.cpp to add a function

void HardwareSerial::clearRXBuffer()
{
_rx_buffer_head = _rx_buffer_tail;
}

faster than that is diificult.

Hello, I have patched HardwareSerial.h and HardwareSerial.cpp in this way:

HardwareSerial.h file
in class 'HardwareSerial : public Stream' below 'public:' I added:

virtual void clearRXBuffer(void);

HardwareSerial.cpp file
under 'Public Methods' I added:

void HardwareSerial::clearRXBuffer()
{
_rx_buffer_head =  _rx_buffer_tail;
}

when compiling I got:

Arduino:1.8.9 (Windows 7), Scheda:"Arduino Uno"

test_clearRXBuffer:27:8: error: 'class HardwareSerial' has no member named 'clearRXBuffer'

Serial.clearRXBuffer();

^~~~~~~~~~~~~

exit status 1
'class HardwareSerial' has no member named 'clearRXBuffer'

I don't know very well C++ language and I appreciate very much who help me, thanks.