2

As serial data bytes are being read from the serial buffer by Serial.read(), are they removed from the Arduino's 64-byte serial buffer altogether?

In my current situation I'm using SoftwareSerial, but this question applies to both software and hardware serial connections.

EDIT: Based on a comment from @dandavis, I'd like to further clarify my question

How does Serial.read() interact with Serial.available()? Let's say that I have the usual setup:

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

What causes Serial.available() to become false?

EDIT 2: Changed question title for even further clarification...

JRiggles
  • 123
  • 5

2 Answers2

2

It is an internal buffer and only the pointer gets increased. It it visible in the source code off the project, located on github:

// Read data from buffer
int SoftwareSerial::read()
{
  if (!isListening())
    return -1;

  // Empty buffer?
  if (_receive_buffer_head == _receive_buffer_tail)
    return -1;

  // Read from "head"
  uint8_t d = _receive_buffer[_receive_buffer_head]; // grab next byte
  _receive_buffer_head = (_receive_buffer_head + 1) % _SS_MAX_RX_BUFF;
  return d;
}

This third line from the bottom is the important part, it wraps back to the beginning if the buffer space has run out. If you call Serial.read(), the pointer is moved to the next position. So with the next Serial.read(), you'll get the next byte, if available. The byte itself gets overwritten only after the wrap (circular buffer).

Majenko
  • 105,851
  • 5
  • 82
  • 139
Stefan M
  • 141
  • 3
0

Calculating how many bytes are available for reading:

int HardwareSerial::available(void)
{
  return ((unsigned int)(SERIAL_RX_BUFFER_SIZE + _rx_buffer_head - _rx_buffer_tail))
}

It's so simple.

Have a look at the Arduino subdir (in your disk) hardware/arduino/avr/cores/arduino. The HardwareSerial.cpp is where you have to look at.