Go Down

Topic: Clearing RX Serial Buffer (Read 170 times) previous topic - next topic

Gosucherry

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

Code: [Select]

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?

Robin2

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
Two or three hours spent thinking and reading documentation solves most programming problems.

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.
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

robtillaart

A non-core patch version could be

Code: [Select]
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.
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Gosucherry

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 :)

void HardwareSerial::clearRXBuffer()
{
  _rx_buffer_head =  _rx_buffer_tail;
}
This is the very thing I was looking for! Thank you. It takes ~8uS :)

robtillaart

Created an issue for this improvement - https://github.com/arduino/Arduino/issues/7254
Rob Tillaart

Nederlandse sectie - http://arduino.cc/forum/index.php/board,77.0.html -
(Please do not PM for private consultancy)

Go Up