Sub topic 7
Buffers and why bytes get lost
This chapter assumes you can write a basic Arduino sketch with setup() and loop(). It also assumes you know the 10-bit 8N1 frame and how baud rate sets bit time from the earlier chapters. The examples use an Arduino Uno (ATmega328P) and the standard AVR core. Other boards differ in buffer size and in a few API details, and the text points those out where it matters.
By the end you will know where a received byte waits before your sketch reads it. You will be able to calculate how long your sketch can ignore the port, and you will recognize the three ways bytes disappear.
Why a buffer exists
The UART hardware delivers one byte roughly every millisecond at 9600 baud. Your loop() might spend 50 ms in a delay(), a sensor read or a display update. If the hardware handed bytes only to code that was already waiting for them, almost everything would be lost.
The Arduino core solves this with a ring buffer (also called a circular buffer). This is a fixed array with two indexes: a head, where new bytes are stored, and a tail, where your sketch reads the oldest byte. Both indexes wrap around to zero at the end of the array, so the same memory is reused forever.
The AVR core keeps two of these per hardware port:
- A receive (RX) buffer, filled by an interrupt service routine (ISR) each time a byte arrives.
- A transmit (TX) buffer, drained by an ISR each time the hardware can accept another byte.
Each buffer is 64 bytes on the Uno. On the smallest AVR chips, with 1 KB of RAM or less, each is 16 bytes. The AVR implementation treats head equal to tail as "empty", so one slot stays unused. A 64-byte array therefore holds at most 63 bytes.
The receive path
A byte passes through several stages between the wire and your variable. Only the last stage is under your control.
On the receive side, the hardware shifts bits into a shift register. When the stop bit is checked, the complete byte moves into a data register. The hardware then raises an interrupt. The ISR copies the byte into the ring buffer and returns. Serial.available() reports how many bytes sit in that ring buffer, and Serial.read() removes the oldest one.
Two points follow from this design.
- The ring buffer fills whether or not your sketch calls
Serial.read(). Reading is the only thing that empties it. - When the ring buffer is full, the ISR throws the new byte away. It does not overwrite old data and it does not signal an error to your sketch. The newest bytes are lost and the oldest are kept.
How long until the buffer is full
At 8N1 each byte takes 10 bit times on the wire (start, 8 data, stop). The time to receive one byte is 10 / baud seconds. The time for your sketch to fall behind by a full buffer is 63 times that, if the sender transmits continuously.
| Baud rate | Time per byte | Time to receive 63 bytes |
|---|---|---|
| 9600 | 1.04 ms | about 65.6 ms |
| 19200 | 0.52 ms | about 32.8 ms |
| 57600 | 0.174 ms | about 10.9 ms |
| 115200 | 0.087 ms | about 5.5 ms |
Raising the baud rate makes the problem worse, because the same buffer represents less time. A delay(100) is harmless at 9600 baud only if the sender is not streaming. At 115200 baud, any code path that takes more than about 5 ms can lose data from a continuous stream.
The numbers assume a continuous stream. Many devices send short bursts with gaps, and the buffer only has to absorb one burst. So the real requirement is: the largest burst you expect must fit in the buffer, or your loop must come back to Serial.read() before the buffer fills.
Seeing the loss happen
This sketch sleeps for half a second between reads. It reports how many bytes it found waiting, then discards them.
void setup() {
Serial.begin(9600);
}
void loop() {
delay(500);
Serial.print(F("available: "));
Serial.println(Serial.available());
while (Serial.available() > 0) {
Serial.read();
}
}Open the Serial Monitor at 9600 baud and send a line of about 200 characters. The monitor's bytes reach the Uno at 9600 baud, so the transfer takes about 200 ms. The buffer fills after 63 bytes, and the remaining bytes are dropped by the ISR. The sketch reports available: 63. A shorter message such as hello reports 6 or 7, depending on the line ending setting, and nothing is lost.
If the output shows a number above 63, the board is not an Uno or compatible with the default 64-byte buffer. Check your board's core for its buffer size.
The transmit buffer and blocking writes
The transmit side works in the opposite direction. Serial.print() and Serial.write() copy bytes into the TX ring buffer and return. An interrupt then feeds the hardware one byte at a time. Your sketch continues while the bytes trickle out.
This only works while there is free space. If the TX buffer is full, Serial.write() waits until the interrupt has sent enough bytes to make room. Your whole sketch stalls during that wait. This sketch measures the stall.
void setup() {
Serial.begin(9600);
char msg[101];
memset(msg, 'x', 100);
msg[100] = '\0';
Serial.println(Serial.availableForWrite());
unsigned long start = micros();
Serial.println(msg);
unsigned long elapsed = micros() - start;
Serial.print(F("println took us: "));
Serial.println(elapsed);
}
void loop() {
}The first line prints the free space, 63 on an Uno. The message is 102 bytes with its line ending, which is more than the buffer holds. The call returns only after about 39 bytes have been sent, so elapsed is close to 40 000 µs. A message under 63 bytes would return in a few tens of microseconds.
Two related calls are easy to confuse:
Serial.availableForWrite()returns how many bytes you can write right now without blocking.Serial.flush()waits until every byte in the TX buffer has been sent. Since Arduino 1.0 it does not clear the receive buffer. To discard unread input you must read it out in a loop.
Use flush() before something that would corrupt the outgoing data, such as entering sleep mode or changing the baud rate. Do not call it routinely after every print. It turns an asynchronous transmit into a blocking one.
Overrun in the hardware
The ring buffer is not the only place a byte can be lost. The UART peripheral itself holds only a small amount of data: the shift register plus one or two bytes in the data register, depending on the chip. The ISR must copy the byte out before the next frame completes. If it does not, the hardware sets an overrun flag and discards the incoming data.
At 9600 baud the ISR has about a millisecond, which is rarely a problem. At 115200 baud it has under 100 µs per byte, so anything that holds off interrupts can cause hardware overrun. Typical causes are:
noInterrupts()sections that run longer than a byte time.- Libraries that disable interrupts for timing-critical output, such as addressable LED strips. A long strip can block interrupts for several milliseconds per update.
- Another ISR that takes a long time to finish.
SoftwareSerial, which blocks other interrupts while it receives (see the chapter on extra serial ports).
The result looks the same as a full buffer: bytes are missing from the stream. The cause is different, and so is the fix. Reading faster does not help when the sketch has the interrupts turned off. You have to shorten or remove the interrupt-off section, or lower the baud rate.
Keeping the buffer empty
The standard pattern is to drain the port on every pass through loop(), move bytes into your own storage, and do the slow work in small steps. This sketch reads newline-terminated lines at 115200 baud while blinking the LED on a millis() timer. It never waits.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
bool tooLong = false;
unsigned long lastToggle = 0;
void setup() {
Serial.begin(115200);
pinMode(LED_BUILTIN, OUTPUT);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
if (tooLong) {
Serial.println(F("line too long, dropped"));
} else {
line[len] = '\0';
Serial.print(F("Got: "));
Serial.println(line);
}
len = 0;
tooLong = false;
} else if (c != '\r') {
if (len < MAX_LEN - 1) {
line[len++] = c;
} else {
tooLong = true;
}
}
}
if (millis() - lastToggle >= 500) {
lastToggle += 500;
digitalWrite(LED_BUILTIN, !digitalRead(LED_BUILTIN));
}
}The inner while loop empties everything that arrived since the last pass, not just one byte. Reading with if instead of while reads one byte per pass of loop(), which is a frequent cause of an apparently "slow" port. The application buffer line has its own limit, and the sketch reports the overflow instead of silently writing past the end of the array.
Note that the sketch prints a reply for each line. If lines arrive faster than the replies can leave, the TX buffer fills and Serial.println() begins to block. Keep replies short, or print only when something is worth reporting.
When draining is not enough
Sometimes the sender produces data faster than your sketch can handle it, or you cannot avoid a long blocking operation. These are the options, in the order you should usually try them.
- Lower the baud rate. If the application does not need 115200, a lower rate gives the loop more time per byte and the ISR more margin.
- Shorten the blocking work. Replace
delay()withmillis()timing. Split long jobs into steps that each return quickly. - Make the sender wait. UART on a basic Uno has no automatic flow control. You can add it in the protocol: the sender sends one message and waits for an acknowledgement or a request before sending the next.
- Enlarge the buffer. On the AVR core the size is a compile-time constant,
SERIAL_RX_BUFFER_SIZE, which you can set with a build flag or by editing the core. It must be a power of two on most cores, and each extra byte costs RAM, which is scarce on an Uno. On ESP32,Serial.setRxBufferSize()changes it at run time, and it must be called beforeSerial.begin(). - Use a board with a larger buffer or a hardware FIFO. Many 32-bit boards have deeper receive FIFOs and more RAM.
A bigger buffer only delays the problem if the average data rate exceeds what your loop can process. It helps with bursts, not with a sustained overload.
Common mistakes
- Using
delay()in a loop that also receives data. - Reading one byte per
loop()pass withif (Serial.available()). - Printing a long debug message on every received byte, which fills the TX buffer and blocks the loop.
- Assuming
Serial.flush()clears input. - Writing into your own char array without a length check.
- Assuming the loss is caused by the wiring, when the sketch is simply too slow. Garbled bytes point to the baud rate or the wiring. Bytes that are simply missing, with the rest intact, point to a buffer or an interrupt problem.
Exercise
A sensor streams data continuously at 57600 baud, 8N1, to an Uno with the default 64-byte buffer (63 usable bytes). Your loop sometimes runs a 20 ms display update. Will bytes be lost, and why?
Show answer
Yes. At 57600 baud one byte takes 10/57600 = about 0.174 ms, so 63 bytes arrive in about 10.9 ms. The 20 ms display update is longer than that, so the buffer fills and the ISR drops the remaining bytes. Fix it by splitting the update into steps under about 10 ms, lowering the baud rate, enlarging the buffer, or having the sender pause.
Exercise
A sketch calls Serial.println() with a 150-character string on an Uno at 9600 baud. Roughly how long does the call block, and which call tells you beforehand how much you can write without blocking?
Show answer
The line is 152 bytes with its line ending. About 63 fit in the TX buffer immediately, so the call waits for roughly 89 bytes to be sent at about 1.04 ms each, which is about 90 ms. Serial.availableForWrite() returns the number of bytes you can write without blocking.