Sub topic 13
Serial buffers and the cost of printing
Every Serial.print() call looks instant, but the board can only send about one byte per millisecond at 9600 baud. This chapter explains where printed bytes wait, when a print call stalls your sketch, and how to keep serial output from disturbing the timing of your program.
It assumes you can write a sketch with setup() and loop(), you know what Serial.begin() and a baud rate do, and you have used millis() for timing.
Where printed bytes go
Serial.print() does not send bytes directly. The Arduino core copies them into a transmit (TX) buffer, a small array in RAM. A hardware block called the UART then sends the bytes out one at a time, driven by an interrupt that fires whenever the UART is ready for the next byte. Your sketch carries on while this happens.
There is a matching receive (RX) buffer for incoming bytes. The UART's interrupt stores each arriving byte there, and Serial.read() takes bytes out of it.
On AVR boards such as the Uno and Nano, both buffers hold 64 bytes. Boards with very little RAM, such as some ATtiny chips, use 16. Other architectures use different sizes, so check the core for your board if the exact number matters.
How fast the buffer drains
Each byte on the wire is sent as 10 bits: one start bit, eight data bits, and one stop bit. So the number of bytes per second is the baud rate divided by 10.
| Baud rate | Bytes per second | Time per byte |
|---|---|---|
| 9600 | 960 | about 1.04 ms |
| 57600 | 5760 | about 174 µs |
| 115200 | 11520 | about 87 µs |
Remember that println() adds two bytes, a carriage return and a newline. A line such as raw=512 volts=2.50 is 18 characters, so println() queues 20 bytes. At 9600 baud those 20 bytes take about 21 ms to leave the board.
If the loop produces bytes faster than the table allows, the buffer fills. The sketch then slows to the speed of the serial line.
When a print call blocks
If the TX buffer has room, Serial.print() copies the bytes and returns within microseconds. If the buffer is full, the call waits until the UART has sent enough bytes to make room. Your sketch is frozen during that wait. Button presses, motor timing, and millis() checks are all delayed.
This sketch measures the difference. It sends one short line that fits in the buffer. It then waits for the buffer to empty and sends three longer lines that cannot all fit.
void setup() {
Serial.begin(9600);
Serial.flush(); // start with an empty buffer
unsigned long t0 = micros();
Serial.println(F("0123456789012345678901234567890123456789")); // 42 bytes
unsigned long fitTime = micros() - t0;
Serial.flush(); // wait until everything is sent
t0 = micros();
for (int i = 0; i < 3; i++) {
Serial.println(F("0123456789012345678901234567890123456789")); // 126 bytes total
}
unsigned long blockTime = micros() - t0;
Serial.flush();
Serial.print(F("one line, fits in buffer: "));
Serial.print(fitTime);
Serial.println(F(" us"));
Serial.print(F("three lines, buffer overflows: "));
Serial.print(blockTime);
Serial.println(F(" us"));
}
void loop() {
}On an Uno at 9600 baud, expect the first number to be in the tens to low hundreds of microseconds. Expect the second to be around 60,000 µs (60 ms). Of the 126 bytes, about 64 fit in the buffer, and the call must wait for the other 62 to be sent, at roughly 1 ms each. Exact values vary by board and core version.
Checking free space before printing
Serial.availableForWrite() returns how many bytes the TX buffer can still accept without blocking. You can use it to skip a print rather than stall. This is useful for debug output in timing-sensitive code, where a missing log line is better than a late motor update.
void setup() {
Serial.begin(9600);
}
void loop() {
int raw = analogRead(A0);
// "raw=1023\r\n" needs at most 10 bytes; require a little extra room
if (Serial.availableForWrite() >= 12) {
Serial.print(F("raw="));
Serial.println(raw);
}
delay(5); // loop runs fast, so many prints are skipped at 9600 baud
}The check must be at least as large as the whole message, because each print() call blocks as soon as it runs out of room. Since this sketch makes two calls (print and println), the 12-byte margin covers both together. If you print several fields per line, build the margin from the worst-case length of the whole line.
What printing costs besides time
Blocking is the largest cost, but not the only one.
- CPU time per byte. The UART interrupt runs once for every byte sent. At 115200 baud that is about 11,500 interrupts per second. Each one is short, but heavy output adds up, and it can disturb code that depends on precise timing.
- Conversion work. Printing a float with
Serial.println(x, 2)converts the number to text on the 8-bit CPU first. This takes more time than printing an integer, and it adds code to the sketch. - Flash and RAM. A string literal like
"Setup complete"takes RAM unless you wrap it inF(), as covered earlier. Many long debug messages can use a large share of the 2 KB on an Uno. - Long lines. Printing
"raw="and"volts="on every pass sends the same label bytes thousands of times. For streaming data, shorter labels or a compact format cost less.
A simple way to see the cost is to time the loop. Count how many times loop() runs per second with and without prints, and compare.
Receive-side limits
The RX buffer has the same 64-byte limit, and it has no blocking behavior. If bytes arrive while the buffer is full, the new bytes are dropped. Your sketch gets no error message, and the data just goes missing.
This happens when the sketch is busy and not calling Serial.read() often enough. A delay(2000) in the loop, followed by a user pasting 100 characters into the Serial Monitor, will lose about 36 of them.
void setup() {
Serial.begin(9600);
}
void loop() {
delay(2000); // too slow to keep up with a long paste
Serial.print(F("Waiting bytes: "));
Serial.println(Serial.available()); // never exceeds 63 or 64
while (Serial.available() > 0) {
Serial.read(); // discard to empty the buffer
}
}Paste a long string while this runs. The reported count stops at the buffer size, not the number you sent.
To avoid losing input, keep each pass of loop() short, drain the buffer on every pass, and use the millis() pattern from the timed-output chapter in place of delay().
Practical rules
- Use the highest baud rate that stays reliable for your board and cable. 115200 is common and cuts the cost per byte by twelve compared with 9600.
- Print less. Send one compact line per interval instead of many short messages.
- Keep the average output rate below
baud / 10bytes per second. If you exceed it, the sketch will eventually block. - Use
availableForWrite()to drop optional debug lines in timing-critical code. - Print at a controlled rate, using
millis()as in the earlier chapter, and avoid printing on every pass of a fast loop. - Remove or disable debug prints in the final version with the macros from the previous chapter.
Exercise
A sketch runs at 9600 baud and calls Serial.println() with the text raw=512 volts=2.50 once per loop pass, with no delay and no other work. About how many times per second can the loop run once the TX buffer is full, and what limits it?
Show answer
The line is 18 characters plus the two bytes added by println, so 20 bytes. At 9600 baud the board sends 960 bytes per second, so it can send about 960 / 20 = 48 lines per second. Once the buffer is full, each print waits for space, so the loop runs about 48 times per second (roughly every 21 ms). The serial line speed is the limit, not the CPU.
Exercise
Why does the sketch using Serial.availableForWrite() >= 12 before printing a 10-byte line use 12 and not 10? What happens if you check for less than the full message length?
Show answer
The margin covers the longest possible message with a little room to spare, so the check is not wrong by a byte or two. If the check is smaller than the message, the free space can run out partway through, and the print call then blocks until the UART frees more room. That is the stall the check was meant to prevent.