Sub topic 10
Designing Messages: Delimiters, Length and Checksum
Assume you know basic Arduino sketches, bytes, binary numbers, and the Serial API. This chapter builds on the fact that UART provides a stream of bytes, not a stream of messages. Your application must decide where one message ends and the next begins.
Why raw bytes need framing
UART sends bytes in order, but it does not preserve application-level boundaries. If a sender writes three separate calls, the receiver may read the bytes in any convenient group:
Sender: "TEMP" "=" "23.5\n"
Receiver: "TE" "MP=23" ".5\n"The receiver needs a framing rule. Framing tells it how to find the start and end of each message, even when data arrives one byte at a time or several messages are already waiting in the receive buffer.
The main choices are:
- A delimiter marks the end of a message.
- A length field states how many payload bytes follow.
- A checksum or cyclic redundancy check (CRC) helps detect corrupted data.
- A robust protocol often combines these methods.
Delimiter-based messages
A delimiter is a reserved byte that marks a boundary. Text protocols commonly use a newline character, \n, to end each message:
SET LED 1\n
GET TEMP\nThis approach is easy to inspect in a serial monitor. The receiver collects characters until it sees the delimiter, then processes the completed line.
A delimiter works well when the payload is text and the delimiter cannot appear unescaped inside a value. If arbitrary binary data is allowed, any byte can occur in the payload. You then need an escaping rule, such as replacing an actual newline with a two-byte escape sequence.
Delimiter protocols have two common failure cases:
- A missing delimiter causes the receiver to wait indefinitely or discard later messages.
- An oversized line can overflow a fixed buffer unless the receiver rejects extra characters.
Length-based messages
A length-based frame puts the payload size in the header:
[0x7E] [length] [payload bytes] [checksum]For example, a length of 3 means that exactly three payload bytes follow. The receiver can then read the known number of bytes instead of searching for a special payload value.
Length fields are useful for binary data and fixed-size buffers. They also make embedded newline or zero bytes harmless. However, a corrupted length can make the receiver wait for too many bytes or interpret later data incorrectly. A start marker and checksum reduce this risk.
For payloads longer than 255 bytes, use a two-byte length or another size that matches your maximum frame. Always reject lengths larger than the receive buffer before copying data.
Checksums detect corruption
A checksum is a value calculated from the frame data. The sender transmits it, and the receiver calculates the same value. If the values differ, at least one byte changed, was lost, or was inserted.
An XOR checksum is small and simple:
uint8_t xorChecksum(const uint8_t *data, uint8_t length) {
uint8_t result = 0;
for (uint8_t i = 0; i < length; i++) {
result ^= data[i];
}
return result;
}XOR is not a strong error detector. Some combinations of changed bits cancel each other out. A CRC detects more error patterns and is preferable when messages matter, cables are noisy, or retransmission is available. Neither checksum can repair a corrupted message. It only lets the receiver reject it.
A complete delimiter-based parser
The following sketch accepts newline-terminated commands. It ignores carriage returns, limits the line length, and processes each complete line without blocking.
const byte MAX_LEN = 32;
char line[MAX_LEN];
byte length = 0;
bool discarding = false;
void handleLine(const char *text) {
Serial.print(F("Received: "));
Serial.println(text);
}
void setup() {
Serial.begin(9600);
}
void loop() {
while (Serial.available() > 0) {
char c = Serial.read();
if (c == '\n') {
if (!discarding) {
line[length] = '\0';
handleLine(line);
}
length = 0;
discarding = false;
} else if (c != '\r') {
if (!discarding) {
if (length < MAX_LEN - 1) {
line[length++] = c;
} else {
discarding = true;
}
}
}
}
}Serial.available() reports how many bytes can be read now. The while loop drains all currently available bytes, but it never waits for a future byte. The null character, '\0', terminates the C string before handleLine() uses it.
When a line exceeds the buffer, discarding prevents a partial command from being processed. The parser waits for the next newline, resets its state, and starts fresh.
Choosing a framing method
| Protocol style | Best for | Main risk |
|---|---|---|
| Newline delimiter | Human-readable text commands | Delimiter must be escaped or forbidden |
| Start marker plus length | Binary or mixed data | Corrupt length can desynchronize parsing |
| Length plus checksum or CRC | Noisy links and important data | More code and protocol definition |
For a simple Arduino control panel, newline-delimited text is often enough. For sensor packets or device-to-device links, use a start marker, bounded length, payload, and checksum. Document the byte order, maximum length, and behavior after a bad frame.
Exercise
A frame begins with 0x7E, contains a one-byte length, a payload, and an XOR checksum. What should the receiver do if the length is larger than its buffer?
Show answer
Reject the frame, discard enough input to resynchronize according to the protocol, and wait for the next valid start marker. It must not copy the payload into the buffer.