Designing a message protocol
Turning a stream of bytes into reliable messages: start markers, length fields, checksums and CRCs, byte order and version numbers, with a working parser.
Lesson 4 of 6 · 35 min · Self-paced · Free
Bytes are not messages
A UART delivers bytes. It does not tell you where one message ends and the next begins, whether a byte was lost, or whether noise flipped a bit. Suppose a microcontroller sends distance readings to a single-board computer as the text "1234\n". It works on the bench. Then a motor starts, a burst of interference corrupts a character, and the computer reads "1294". Nothing in that text says it is wrong.
A message protocol is the set of rules both sides agree on for packaging data so the receiver can find messages, check them, and reject the damaged ones. Designing one well is a core embedded skill, and the same ideas appear in every network protocol you will ever use.
The parts of a frame
A typical binary frame looks like this:
| START | VERSION | TYPE | LENGTH | PAYLOAD (LENGTH bytes) | CRC (2 bytes) |- Start marker: a fixed byte, such as 0xAA, that says "a frame might begin here". It lets a receiver that joins mid-stream, or loses a byte, find its place again.
- Version: which edition of the protocol this frame follows, so you can change the format later without confusing old devices.
- Type: what kind of message this is: a distance reading, a motor command, an error report.
- Length: how many payload bytes follow. The receiver knows exactly where the frame ends without needing a special terminator.
- Payload: the data itself.
- Check value: a checksum or CRC calculated from the other bytes, so the receiver can detect corruption.
Packing numbers: byte order
A 16-bit number such as 1234 (0x04D2) occupies two bytes, and the two sides must agree on their order. Little-endian sends the low byte first (D2 04); big-endian sends the high byte first (04 D2). Neither is "right", but mixing them up turns 1234 into 53764. Write the byte order into the protocol's documentation. Python's standard struct module packs and unpacks values with an explicit order: "<" means little-endian, "H" an unsigned 16-bit value and "I" an unsigned 32-bit value.
Checksums and CRCs
The simplest check value is a sum: add all the bytes and keep the low 8 bits. It catches many single-byte errors but has blind spots. Since addition does not care about order, swapping two bytes gives the same sum.
A cyclic redundancy check (CRC) is a stronger, still cheap, calculation based on polynomial division of the data's bits. A 16-bit CRC detects every single-bit and double-bit error in a message of moderate length, every burst error up to 16 bits long (which includes two neighbouring bytes swapped). Python's standard library includes a common 16-bit CRC as binascii.crc_hqx:
import struct
import binascii
START = 0xAA
VERSION = 1
MSG_DISTANCE = 0x10
def checksum8(data):
"""Simple checksum: sum of all bytes, keeping only the low 8 bits."""
return sum(data) & 0xFF
def crc16(data):
"""CRC-16/CCITT-FALSE from the standard library."""
return binascii.crc_hqx(data, 0xFFFF)
def build_frame(msg_type, payload):
body = bytes([VERSION, msg_type, len(payload)]) + payload
return bytes([START]) + body + struct.pack("<H", crc16(body))
# Payload: distance in millimetres (uint16) and a timestamp in ms (uint32),
# both little-endian.
payload = struct.pack("<HI", 1234, 56789)
frame = build_frame(MSG_DISTANCE, payload)
print("frame:", frame.hex(" "))
# A swap of two payload bytes fools the simple sum, but not the CRC.
good = bytes([0x01, 0x02, 0x03])
swapped = bytes([0x02, 0x01, 0x03])
print("sum :", hex(checksum8(good)), hex(checksum8(swapped)))
print("crc16:", hex(crc16(good)), hex(crc16(swapped)))
print("check value:", hex(crc16(b"123456789")))Output:
frame: aa 01 10 06 d2 04 d5 dd 00 00 b1 fa
sum : 0x6 0x6
crc16: 0xadad 0xa1ae
check value: 0x29b1Read the frame byte by byte: start 0xAA, version 1, type 0x10, length 6, then 1234 as d2 04, then 56789 (0x0000DDD5) as d5 dd 00 00, then the CRC 0xFAB1 sent low byte first. The last line is a useful habit: CRCs come in many variants, and each has a published check value, its result for the ASCII text "123456789". If your C implementation on the microcontroller gives 0x29B1 for that string too, both sides are computing the same CRC.
Note that a CRC detects accidental errors. It is not security: anyone can compute a valid CRC for a forged message. Protecting against deliberate tampering needs cryptographic authentication, a topic of its own.
Writing a receiver that resynchronises
The receiver is where the design pays off. It scans for the start byte, reads the header, checks that the version and length are sensible, waits for the whole frame, and verifies the CRC. If anything fails, it moves forward one byte and searches again, because the 0xAA it found might have been an ordinary data byte rather than a real start.
MAX_PAYLOAD = 32
def parse_stream(stream):
"""Yield (msg_type, payload) for every valid frame found in a byte stream."""
i = 0
while i < len(stream):
if stream[i] != START:
i += 1 # not a frame start: skip one byte
continue
if i + 4 > len(stream):
break # header incomplete: wait for more bytes
version, msg_type, length = stream[i + 1], stream[i + 2], stream[i + 3]
end = i + 4 + length + 2
if version != VERSION or length > MAX_PAYLOAD:
i += 1 # implausible header: resynchronise
continue
if end > len(stream):
break
body = stream[i + 1: i + 4 + length]
(received,) = struct.unpack("<H", stream[end - 2: end])
if crc16(body) == received:
yield msg_type, body[3:]
i = end
else:
print(f"bad CRC in frame at byte {i}, skipping")
i += 1
a = build_frame(0x10, struct.pack("<HI", 1234, 56789))
b = bytearray(build_frame(0x10, struct.pack("<HI", 1240, 56889)))
b[5] ^= 0x04 # flip one bit "in transit"
c = build_frame(0x10, struct.pack("<HI", 1251, 56989))
stream = bytes([0x37, 0xAA, 0x99]) + a + bytes(b) + c
for msg_type, payload in parse_stream(stream):
mm, ms = struct.unpack("<HI", payload)
print(f"type 0x{msg_type:02X}: {mm} mm at t = {ms} ms")Run this after the code above (it reuses START, VERSION, crc16, build_frame and struct). This part prints:
type 0x10: 1234 mm at t = 56789 ms
bad CRC in frame at byte 15, skipping
type 0x10: 1251 mm at t = 56989 msThe stream starts with junk, including a stray 0xAA that is rejected because the next byte is not a valid version. The first real frame is decoded. The second has one flipped bit, so its CRC fails and it is dropped rather than delivered as a wrong distance. The receiver then finds the third frame. In firmware, the same logic is usually written as a state machine that processes one byte at a time as each arrives from the UART, which you met in the programming-foundations module.
Design decisions worth making early
- Maximum length: cap the payload size so a corrupted length byte cannot make the receiver wait for thousands of bytes.
- Versioning: put a version field in from day one. Adding it later is much harder than ignoring it now.
- Units and scaling: send integers in documented units (millimetres, milliseconds) rather than floats, as in the fixed-point lesson.
- Timestamps: include the time each measurement was taken, not when it was sent.
- Sequence numbers: a counter that increases with each frame lets the receiver detect lost frames.
- What happens on error: decide whether the receiver silently drops, logs, or asks for a resend. For commands that move motors, a dropped frame is usually safer than a guessed one.
- Byte stuffing: an alternative to length fields is to reserve the start byte and escape it wherever it appears in data. Schemes such as COBS (consistent overhead byte stuffing) do this efficiently.
Recap
A protocol turns a byte stream into checkable messages. A start marker lets the receiver find frames, a length field says where they end, a version field allows change, and a CRC detects corruption far better than a simple sum. Document byte order and units, cap the payload length, and write a receiver that resynchronises by stepping forward one byte when anything is wrong. A damaged message should be dropped, never delivered.
Project
Python project: design and break your own protocol
- Design a frame for a small robot that sends three values: a battery voltage in millivolts, a motor speed in revolutions per minute (which can be negative), and a status byte. Write a one-page specification listing every field, with its size, byte order, units and range.
- Implement
build_frameand a resynchronisingparse_streamfor it in Python, usingstructandbinascii.crc_hqx. - Write a test that builds 100 frames, then corrupts the stream in several ways: flip random bits, delete a byte, insert junk, swap two bytes. Use
random.seed(1)so your results repeat. Count how many frames are decoded correctly, how many are rejected, and confirm none are decoded wrongly. - Repeat with the simple 8-bit sum instead of the CRC and compare.
This is a computer-only activity. No hardware is needed.
Deliverables
- A written frame specification
- Python builder, parser and corruption tests
- Counts of good, rejected and wrongly accepted frames for the CRC and the simple sum
Adult supervision requiredThis is a software-only project; the battery and motor values are invented numbers. If you later send these frames from real hardware, use only low-voltage, battery-powered boards, keep any motors small and secured, and work with an adult supervising.
Knowledge check
Check your understanding
Go further
- struct — Python documentation ↗
Format characters and byte-order prefixes for packing binary data.
- binascii — Python documentation ↗
Includes crc_hqx and crc32 for computing CRCs.
- Cyclic redundancy check — Wikipedia ↗
How CRCs work and which errors they are guaranteed to detect.
- Consistent Overhead Byte Stuffing — Wikipedia ↗
An efficient alternative framing method using byte stuffing.
Lesson materials · free to download
Sign in to track your progress. Reading is free without an account.