Sub topic 10
Designing Messages: Delimiters, Length and Checksum
UART delivers a stream of bytes. It has no idea where one message ends and the next begins, and it does not promise that the bytes arrive intact. This chapter shows how to add that structure yourself.
This chapter assumes you know the following:
- How a UART frame carries one byte (start, data, stop bits).
- How to use
Serial.available()andSerial.read(). - How the non-blocking line reader from the previous chapter works.
- Basic C++ and bitwise operators such as XOR (
^).
Why a byte stream needs structure
Suppose a sensor board sends the bytes 0x12 0x34 0x56 0x78 repeatedly. If the receiver starts listening in the middle, it may read 0x56 0x78 0x12 0x34 and treat it as a valid value. Nothing at the UART level reveals the mistake.
A message format must answer three questions:
- Where does a message start and end? This is framing.
- How many bytes belong to it? This is length.
- Did it arrive intact? This is integrity.
Do not confuse this with the UART frame, which is the start bit, data bits and stop bit around a single byte. A message is a sequence of many such bytes, so this is a second, higher layer.
Option 1: delimiters
A delimiter is a reserved byte that marks the end of a message. The most common choice is the newline (\n). The line reader from the previous chapter uses it, and so does everything you type in the Serial Monitor.
Delimiters suit human-readable data:
T=23.5,H=41Their strengths are that you can read them in a terminal, test them by typing, and add new fields easily. They have three weaknesses:
- The delimiter must never appear inside the data. Text rarely contains
\n, but a raw binary value can be any byte from 0 to 255, including0x0A. - Text costs more bytes. The number
1000takes four characters but fits in two bytes of binary. - Parsing takes work. Converting text to numbers costs flash and CPU time on small boards.
If you need to send arbitrary binary data with a delimiter, you must use byte stuffing (also called escaping). The sender replaces any payload byte that equals the delimiter or the escape byte with a two-byte sequence. SLIP and HDLC use this approach. It works, but it makes the length of the encoded message unpredictable.
Text protocols can still carry a checksum. GPS receivers send NMEA sentences such as $GPGLL,...*4F\r\n. The $ marks the start, * introduces a two-digit hexadecimal XOR checksum, and the line ending marks the end.
Option 2: a length prefix
Instead of looking for an end marker, the sender says in advance how many bytes follow. The receiver reads the length, then reads exactly that many bytes.
Because the receiver counts bytes, the payload may contain any value, including a byte equal to a start marker. No escaping is needed.
The weakness is that a damaged length byte throws the receiver off. If the length says 200 but the sender meant 4, the receiver waits for bytes that never come, and it may swallow the start of the next message. Two defences address this:
- A maximum length. Reject any length larger than your buffer, and reject zero if empty payloads are not allowed.
- A timeout. If the next byte does not arrive within a set time, abandon the partial message.
A start marker for resynchronization
A length prefix alone does not tell a receiver that has just powered up where a message begins. The fix is to put a fixed start marker byte in front. The receiver discards bytes until it sees the marker. After any error it returns to this state and waits for the next marker, which is called resynchronizing.
A marker byte can also appear inside a payload. The receiver can therefore mistake a payload byte for a marker, but only after an error has already put it out of step. The length and checksum make such a false start unlikely to survive, and the receiver recovers at the next real marker.
Checksums: detecting damage
A checksum is a small value computed from the payload. The sender appends it, and the receiver recomputes it. If the two values differ, the message was damaged and the receiver discards it.
Even on a short, clean wire, damage happens. Noise from motors or long cables can flip bits. The receiver may also lose bytes if its buffer overflows, as the earlier chapter on buffers explained.
| Method | Size | How it works | Catches | Misses |
|---|---|---|---|---|
| Parity bit (per byte) | 1 bit | Even or odd count of 1 bits | Any single flipped bit in a byte | Two flipped bits in the same byte |
| XOR of all bytes | 1 byte | XOR every payload byte together | Any single flipped bit | Two flips in the same bit position of different bytes, and swapped bytes |
| Sum (mod 256) | 1 byte | Add every byte, keep the low 8 bits | Most single-byte errors | Swapped bytes, compensating errors |
| CRC-8 | 1 byte | Polynomial division over the bits | All single-bit errors, all burst errors up to 8 bits, most others | Rare random patterns |
| CRC-16 | 2 bytes | Same, with a 16-bit polynomial | Longer bursts, far fewer misses | Rarer still |
XOR is the cheapest to compute, and it is enough for a short cable on a bench. For a noisy environment or longer messages, use a CRC.
This is a CRC-8 routine (polynomial 0x07, initial value 0) that you can use in place of xorChecksum:
uint8_t crc8(const uint8_t *data, uint8_t len) {
uint8_t crc = 0;
for (uint8_t i = 0; i < len; i++) {
crc ^= data[i];
for (uint8_t bit = 0; bit < 8; bit++) {
if (crc & 0x80) {
crc = (uint8_t)((crc << 1) ^ 0x07);
} else {
crc = (uint8_t)(crc << 1);
}
}
}
return crc;
}For the ASCII bytes "123456789", this routine returns 0xF4. You can use that value as a test for your implementation.
A complete frame format
This chapter's binary format uses four fields:
| Field | Size | Purpose |
|---|---|---|
| Start marker | 1 byte, always `0x7E` | Lets the receiver find the beginning |
| Length | 1 byte, 1 to 32 | Number of payload bytes |
| Payload | Length bytes | The data itself |
| Checksum | 1 byte | XOR of the payload bytes |
The overhead is three bytes per message. At 9600 baud with 8N1 framing, each byte takes 10 bit times, about 1.04 ms. A frame with a 4-byte payload is 7 bytes and takes about 7.3 ms on the wire.
This format checksums only the payload. A corrupted length byte is therefore not covered directly. The receiver notices indirectly, because the checksum it reads will almost always be the wrong byte, and it resynchronizes. If you want direct protection, include the length byte in the checksum.
The sender
The sender builds on the sendFrame function from earlier. This complete sketch sends a changing 4-byte payload once per second.
uint8_t xorChecksum(const uint8_t *data, uint8_t len) {
uint8_t sum = 0;
for (uint8_t i = 0; i < len; i++) {
sum ^= data[i];
}
return sum;
}
void sendFrame(const uint8_t *payload, uint8_t len) {
Serial.write((uint8_t)0x7E);
Serial.write(len);
Serial.write(payload, len);
Serial.write(xorChecksum(payload, len));
}
uint8_t counter = 0;
void setup() {
Serial.begin(9600);
}
void loop() {
uint8_t payload[4] = {0x01, 0x7E, counter, 0xFF};
sendFrame(payload, sizeof(payload));
counter++;
delay(1000);
}The second payload byte is 0x7E on purpose. It is the same as the start marker, and the length prefix lets the receiver handle it correctly.
The receiver as a state machine
The receiver reads one byte at a time and moves through four states. This design never blocks: each byte either advances the state or sends the receiver back to waiting for a marker.
For testing, the receiver below listens on pins 10 and 11 with SoftwareSerial and prints results to the USB Serial Monitor. This keeps debugging output off the data link. Connect the sender board's TX pin to pin 10 on the receiver board, and connect the two grounds. If the boards run at different voltages, add level shifting as described in the wiring chapter.
#include <SoftwareSerial.h>
const uint8_t START_BYTE = 0x7E;
const uint8_t MAX_PAYLOAD = 32;
const unsigned long TIMEOUT_MS = 100;
enum State : uint8_t { WAIT_START, WAIT_LEN, READ_PAYLOAD, WAIT_CHECKSUM };
SoftwareSerial link(10, 11); // RX, TX
State state = WAIT_START;
uint8_t payload[MAX_PAYLOAD];
uint8_t expectedLen = 0;
uint8_t received = 0;
unsigned long lastByteMs = 0;
uint8_t xorChecksum(const uint8_t *data, uint8_t len) {
uint8_t sum = 0;
for (uint8_t i = 0; i < len; i++) {
sum ^= data[i];
}
return sum;
}
void handlePayload(const uint8_t *data, uint8_t len) {
Serial.print(F("Frame OK, "));
Serial.print(len);
Serial.print(F(" bytes:"));
for (uint8_t i = 0; i < len; i++) {
Serial.print(' ');
Serial.print(data[i], HEX);
}
Serial.println();
}
void feed(uint8_t b) {
switch (state) {
case WAIT_START:
if (b == START_BYTE) {
state = WAIT_LEN;
}
break;
case WAIT_LEN:
if (b == 0 || b > MAX_PAYLOAD) {
state = WAIT_START;
} else {
expectedLen = b;
received = 0;
state = READ_PAYLOAD;
}
break;
case READ_PAYLOAD:
payload[received++] = b;
if (received == expectedLen) {
state = WAIT_CHECKSUM;
}
break;
case WAIT_CHECKSUM:
if (b == xorChecksum(payload, expectedLen)) {
handlePayload(payload, expectedLen);
} else {
Serial.println(F("Bad checksum, frame dropped"));
}
state = WAIT_START;
break;
}
}
void setup() {
Serial.begin(9600);
link.begin(9600);
}
void loop() {
while (link.available() > 0) {
lastByteMs = millis();
feed((uint8_t)link.read());
}
if (state != WAIT_START && millis() - lastByteMs > TIMEOUT_MS) {
state = WAIT_START;
}
}The expected output once per second is:
Frame OK, 4 bytes: 1 7E 0 FF
Frame OK, 4 bytes: 1 7E 1 FFHandling errors and edge cases
- Partial frames after power-up. The receiver starts in
WAIT_STARTand discards everything until it sees0x7E. A reset mid-message costs at most one message. - Lost bytes. If a byte disappears, the receiver reads the checksum from the wrong position and rejects the frame. It then returns to
WAIT_START. The next frame is received normally. - Silent stalls. The timeout covers the case where the sender stops half-way. Without it, the receiver would take the first bytes of the next frame as the rest of the old one.
- Wasted bytes on rejection. After a bad checksum, the bytes of the rejected frame are already consumed. If the stream carries a real marker inside those bytes, the receiver misses that frame. For most hobby links this is acceptable. A stricter design buffers the whole frame and rescans it for a marker.
- Buffer limits. Always bound the payload length by the size of your buffer. Writing past the end of
payloadcorrupts memory, and a bad length byte would otherwise trigger it. - Byte-width mistakes. Multi-byte values such as a 16-bit integer must be split into bytes in an agreed order. Pick big-endian or little-endian and document it. Mismatched byte order is one of the most common bugs when a Python or PC program talks to an Arduino.
- Framing errors versus checksum errors. The UART hardware detects framing errors per byte (a bad stop bit), as covered earlier. The checksum detects errors per message. They protect against different faults, so use both.
Choosing a format
| Situation | Suggested format |
|---|---|
| Debugging, commands typed by a person | Newline-terminated text |
| Text with some protection against noise | Text line with an appended checksum, as NMEA does |
| Small binary values, controlled cable | Start marker, length, payload, XOR |
| Noisy environment or long cable | Start marker, length, payload, CRC-8 or CRC-16 |
| Arbitrary binary data with delimiters only | Delimiter plus byte stuffing |
A checksum can only detect errors. It does not correct them. If a message matters, the protocol needs a reply (an acknowledgement) and a way to resend, and those features go beyond the framing described here.
Exercise
A receiver using the frame format in this chapter sees these bytes: 7E 03 0A 0B 0C 05. The checksum is the XOR of the payload bytes. Is the frame valid? If not, what checksum byte should the sender have used?
Show answer
The payload is 0A, 0B, 0C. 0A XOR 0B = 01, and 01 XOR 0C = 0D. The correct checksum is 0x0D, but the frame has 0x05, so the receiver rejects it. The 0x05 would indicate corruption in the payload or the checksum byte.
Exercise
A sender transmits a frame with a 10-byte payload at 115200 baud using 8N1. How many bytes are on the wire, and about how long does the frame take? Round to the nearest tenth of a millisecond.
Show answer
The frame has 1 start byte, 1 length byte, 10 payload bytes and 1 checksum byte, which is 13 bytes. Each byte takes 10 bit times (start, 8 data, stop), so the frame is 130 bits. At 115200 baud that is 130 / 115200 = 0.00113 s, about 1.1 ms.
Exercise
Why does a length-prefixed format let a payload contain the byte 0x7E safely, while a format that ends messages with a delimiter byte needs escaping for the same byte?
Show answer
The length-prefixed receiver counts bytes and never inspects the payload for a marker, so any value is acceptable inside the counted region. A delimiter-based receiver treats the delimiter value as the end of the message wherever it appears, so a payload byte with that value would end the message early unless the sender escapes it.