Sub topic 8
Reading and Parsing Incoming Data Without Blocking
Assume you know basic Arduino sketches, bytes, digital levels, and C or C++ syntax. This chapter focuses on turning the incoming UART byte stream into complete messages while allowing the rest of your program to keep running.
The problem with waiting
UART delivers bytes one at a time. A message such as TEMP=23.5\n may arrive over several calls to loop(). Your sketch must collect those bytes until it knows that the message is complete.
A blocking parser waits for the rest of a message before doing anything else. For example, a loop that waits until Serial.available() becomes nonzero can prevent a motor from being updated or a button from being checked. A non-blocking parser checks for available bytes, handles the bytes that have already arrived, and then returns to the main program.
Use Serial.available() to ask how many bytes are waiting in the receive buffer. Use Serial.read() only when at least one byte is available.
Newline-terminated messages
A simple text protocol uses a newline character as the delimiter, or boundary, between messages. The sender might transmit:
LED ON\n
LED OFF\nThe receiver stores characters in a buffer. When it receives \n, it adds a null character, \0, and treats the buffer as a C string.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte len = 0;
void handleLine(const char *text) {
if (strcmp(text, "LED ON") == 0) {
digitalWrite(LED_BUILTIN, HIGH);
} else if (strcmp(text, "LED OFF") == 0) {
digitalWrite(LED_BUILTIN, LOW);
} else {
Serial.print(F("Unknown command: "));
Serial.println(text);
}
}
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') {
if (len < MAX_LEN - 1) {
line[len++] = c;
} else {
// Discard this overlong line until its newline arrives.
len = 0;
}
}
}
// Other work can run on every pass through loop().
}while processes every byte currently waiting, but it does not wait for a future byte. After the buffer is empty, the loop continues with the rest of loop().
The \r check handles carriage return characters. Many terminals send a pair, \r\n, when you press Enter. Ignoring \r lets the same parser accept both Unix-style and Windows-style line endings.
Protecting the buffer
The expression MAX_LEN - 1 reserves one position for \0. Without that space, functions such as strcmp() and Serial.println() could read beyond the array. Reading or writing beyond an array is a buffer overflow. It can corrupt unrelated variables and cause unpredictable behavior.
The example resets the buffer when a line is too long. It then ignores the remaining characters until the next newline. This is safer than partially executing a command. Another valid policy is to set an overflowed flag and report an error when the delimiter arrives.
Parsing a line safely
Receiving a complete line and interpreting it are separate tasks:
- The receiver collects bytes and finds a delimiter.
- The handler validates the complete text.
- The handler performs an action only when the text is valid.
For values, parse and validate the range. For example, a command SET 75 should reject missing numbers, extra unexpected text, and values outside the allowed range. Avoid assuming that a message is complete merely because one byte has arrived.
The parsing flow
Choosing a message boundary
Newline parsing works well for human-readable commands. It does not work when payloads may contain newlines unless you escape those characters or use another protocol.
For machine-to-machine data, common alternatives are:
- A fixed-length message, where every message has exactly the same number of bytes.
- A length-prefixed message, where the first byte says how many payload bytes follow.
- A start marker followed by a length and checksum.
Whichever format you choose, the receiver needs a way to recover after a missing or corrupted byte. A parser should be able to discard data and search for the next valid boundary.
Exercise
Why does the example use while (Serial.available() > 0) instead of waiting in a loop until a newline arrives?
Show answer
It processes bytes that have already arrived and then returns to the rest of the program. Waiting for a newline would block other work while the sender is still transmitting.