Sub topic 8
Reading and Parsing Incoming Data Without Blocking
This chapter assumes you can write a basic Arduino sketch with setup() and loop(). It also assumes you know what a byte is and how a UART frame and its receive buffer work, as covered in earlier chapters. Here you will learn how to pull bytes out of the receive buffer without stalling your sketch, and how to turn those bytes into complete, safe messages.
Why blocking reads cause trouble
A UART delivers bytes one at a time, at a speed set by the baud rate. At 9600 baud with an 8N1 frame (10 bits per byte), one byte arrives roughly every 1.04 ms. Your sketch can run thousands of instructions in that time. If your code waits for the next byte, it wastes all of that time and cannot do anything else, such as blink an LED, read a sensor or update a display.
Some Arduino functions wait for you. Serial.readString(), Serial.parseInt(), Serial.parseFloat() and Serial.readBytesUntil() all block until they get enough data or a timeout expires. The default timeout is 1000 ms, set by Serial.setTimeout(). A sketch that calls Serial.parseInt() once per loop pass can freeze for a full second whenever a number is incomplete.
A non-blocking approach has one rule: only read what is already in the buffer, then return to loop() immediately.
The core tool: `Serial.available()`
Serial.available() returns the number of bytes that have already arrived and are waiting in the receive buffer. It never waits. Serial.read() returns the first waiting byte as an int, or -1 if the buffer is empty. Together they give you a safe pattern:
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
int b = Serial.read();
// Handle one byte here.
Serial.write(b);
}
// Other work can run here on every pass.
}Two details matter.
Serial.read()removes the byte from the buffer. You cannot read it twice. UseSerial.peek()if you only want to look at the next byte without removing it.- The return type is
int, notchar. A valid byte is 0 to 255, and-1signals "nothing there". If you store the result straight into acharorbytewithout checkingavailable()first, an empty read looks like a real byte (255 asbyte, or -1 aschar).
The pattern is: check available(), read one byte, handle it, repeat. The loop ends as soon as the buffer is empty.
Accumulating a line into a buffer
Most text protocols end each message with a newline character (\n). The usual technique is to collect characters into a fixed-size array until the newline arrives. Then you process the whole line.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
void handleLine(const char *text) {
Serial.print(F("Got: "));
Serial.println(text);
}
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
line[len] = '\0';
handleLine(line);
len = 0;
} else if (c != '\r' && len < MAX_LEN - 1) {
line[len++] = c;
}
}
}Each part of this sketch has a reason.
line[len] = '\0'turns the collected characters into a valid C string. Functions such asstrcmp(),atoi()andSerial.println()need that terminating zero.len < MAX_LEN - 1leaves one slot free for the terminator and stops the array from overflowing. Characters past the limit are dropped.c != '\r'ignores carriage returns. The Arduino Serial Monitor can send\n,\r, or both (\r\n), depending on its line-ending setting. Skipping\rmakes the code work with all three.len = 0resets the state so the next line starts clean.
The variables line and len keep their values between calls to loop(). That is how the sketch remembers a half-received line while it does other work. This is a small state machine: the state is "how many characters have I collected so far".
Dealing with overlong lines
The sketch above silently drops characters when a line is too long. The shortened line is then processed as if it were complete, which can cause wrong behavior. A safer design marks the line as bad and discards it at the newline.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
bool overflow = false;
void handleLine(const char *text) {
Serial.print(F("Got: "));
Serial.println(text);
}
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
if (overflow) {
Serial.println(F("Line too long, ignored"));
} else {
line[len] = '\0';
handleLine(line);
}
len = 0;
overflow = false;
} else if (c != '\r') {
if (len < MAX_LEN - 1) {
line[len++] = c;
} else {
overflow = true;
}
}
}
}Choose the policy that fits your protocol. Rejecting an overlong line is usually safer than acting on a truncated one, especially for commands that change hardware state.
Parsing the line
Once you have a complete C string, parse it with ordinary C functions. These work on data already in memory, so none of them block.
Suppose commands look like LED 1 or SPEED 120. This handler splits the text at the first space.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
void handleLine(char *text) {
char *arg = strchr(text, ' ');
if (arg != NULL) {
*arg = '\0'; // end the command word
arg++; // arg now points at the text after the space
}
if (strcmp(text, "LED") == 0 && arg != NULL) {
int value = atoi(arg);
digitalWrite(LED_BUILTIN, value != 0 ? HIGH : LOW);
Serial.println(F("OK"));
} else if (strcmp(text, "SPEED") == 0 && arg != NULL) {
long value = strtol(arg, NULL, 10);
Serial.print(F("Speed set to "));
Serial.println(value);
} else {
Serial.println(F("ERR unknown command"));
}
}
void setup() {
pinMode(LED_BUILTIN, OUTPUT);
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
line[len] = '\0';
handleLine(line);
len = 0;
} else if (c != '\r' && len < MAX_LEN - 1) {
line[len++] = c;
}
}
}Useful C functions for this work:
| Function | Purpose | Note |
|---|---|---|
| `strchr(s, c)` | Find the first occurrence of a character | Returns `NULL` if not found |
| `strcmp(a, b)` | Compare two strings | Returns 0 when equal |
| `strtok(s, delims)` | Split into tokens | Modifies the string; not safe to nest |
| `atoi(s)` | Convert text to `int` | Returns 0 for bad input, so you cannot tell "0" from an error |
| `strtol(s, &end, 10)` | Convert text to `long` | Sets `end` to the first unparsed character, so you can check for errors |
| `atof(s)` | Convert text to `float` | Same problem as `atoi()` |
If you need to detect invalid numbers, use strtol() and compare end with the start of the string. If they are equal, no digits were read.
Choosing between `String` and C strings
Arduino's String class is convenient, but it allocates memory on the heap and releases it again. On boards with little RAM, such as the Uno with 2 KB, repeated growth and shrinkage can fragment the heap and eventually cause lockups that are hard to trace. Fixed char arrays use a known amount of memory and never fragment. For long-running sketches that parse serial data, prefer char arrays.
Reading binary data without blocking
Binary data has no newline to wait for, so you need to know how many bytes to expect. The same idea applies: keep the state in global variables and consume only what is available.
const byte FRAME_LEN = 4;
byte frame[FRAME_LEN];
byte count = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
frame[count++] = Serial.read();
if (count == FRAME_LEN) {
uint16_t a = (uint16_t)frame[0] << 8 | frame[1];
uint16_t b = (uint16_t)frame[2] << 8 | frame[3];
Serial.print(a);
Serial.print(' ');
Serial.println(b);
count = 0;
}
}
}This reads two 16-bit big-endian numbers per 4-byte frame. It has a weakness: if the sender and receiver start out of step (for example, you reset the receiver in the middle of a frame), every later frame is misaligned and nothing tells you. A later chapter on message framing adds a start marker and checksum to fix this.
Using timeouts without blocking
A line that never gets its newline leaves your buffer half full forever. Detect this with millis(), which returns the milliseconds since the board started. Record when the last byte arrived. If too long passes without a new byte, throw away the partial data.
const byte MAX_LEN = 32;
const unsigned long IDLE_LIMIT_MS = 500;
char line[MAX_LEN];
byte len = 0;
unsigned long lastByteAt = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
lastByteAt = millis();
if (c == '\n') {
line[len] = '\0';
Serial.print(F("Got: "));
Serial.println(line);
len = 0;
} else if (c != '\r' && len < MAX_LEN - 1) {
line[len++] = c;
}
}
if (len > 0 && millis() - lastByteAt > IDLE_LIMIT_MS) {
len = 0;
Serial.println(F("Partial line discarded"));
}
}The subtraction millis() - lastByteAt works correctly even when millis() wraps around after about 49 days, because both values are unsigned. Do not rewrite it as millis() > lastByteAt + IDLE_LIMIT_MS, which fails at the wraparound.
Common errors
- Reading without checking
available().Serial.read()returns-1on an empty buffer. Stored in achar, that becomes a junk character that your parser may treat as input. - Using
readString()in a busy sketch. It waits for the timeout, so every incomplete message costs you up to a second. - Reading only one byte per
loop()pass. Ifloop()takes long, the 64-byte receive buffer on most AVR boards fills and the hardware drops new bytes. Usewhile, notif, to drain the buffer. - Forgetting the terminator. Without
'\0',strcmp()andprintln()read past your data into whatever memory follows. - Writing past the array. A missing length check overwrites other variables and causes strange, unrelated bugs.
- Slow
loop()with long delays. Adelay(500)in the loop means that at 115200 baud, about 5760 bytes can arrive while you sleep. The buffer holds 64. Remove the delays or usemillis()timing. - Line ending mismatch. If the sender uses only
\r, a parser that waits for\nnever fires. Check what the other device actually sends.
Putting it together
A robust non-blocking reader follows these steps on every pass through loop():
- Drain the receive buffer with a
while (Serial.available() > 0)loop. - Store each byte in a fixed-size array, with a length check.
- When the end-of-message marker arrives, terminate the string and hand it to a parser.
- Reset the length so the next message starts fresh.
- Use
millis()to discard partial messages that stall. - Return from
loop()quickly so other tasks keep running.
Exercise
A sketch calls Serial.parseInt() inside loop() while also blinking an LED with millis() timing. The LED blinks irregularly whenever the sender transmits a number slowly. Why does this happen, and how would you change the sketch?
Show answer
Serial.parseInt() blocks until it reads a complete number or the 1000 ms timeout expires. While it waits for a slow sender, loop() cannot reach the LED code, so the blink timing slips. Replace it with a non-blocking reader. Drain Serial.available() byte by byte into a fixed char array, and when the newline arrives, terminate the string and convert it with strtol(). The LED code then runs on every pass of loop().
Exercise
The line reader below uses if (Serial.available() > 0) instead of while. The sender transmits 20-character lines at 115200 baud, and loop() also does 30 ms of other work per pass. What goes wrong?
Show answer
The sketch reads one byte per pass, about 30 ms each. At 115200 baud (10 bits per byte), a byte arrives every 87 µs, so bytes pile up far faster than they are read. The 64-byte receive buffer on most AVR boards fills after a few passes, and the hardware drops the rest. Lines are lost or corrupted. Using while (Serial.available() > 0) drains everything that has arrived on each pass, and shortening the 30 ms of other work keeps the buffer from filling between passes.
Exercise
Why is millis() - lastByteAt > IDLE_LIMIT_MS preferred over millis() > lastByteAt + IDLE_LIMIT_MS?
Show answer
Both values are unsigned, so the subtraction gives the correct elapsed time even after millis() wraps around to zero (about every 49 days). The addition form can overflow or compare against a wrapped value, which makes the timeout fire at the wrong time or never fire.