Home / Learn Chip Programming / Designing a Serial Protocol: Framing, CRC and Parsing
Designing a Serial Protocol: Framing, CRC and Parsing
Create a robust binary or text protocol between devices or with a PC.
Theory in plain words
What it is
A good protocol has a start marker, length, command ID, payload, CRC and optional sequence number. Text protocols (AT commands, NMEA, JSON lines) are easier to debug; binary protocols are compact.
Why we use it
Every product talks to something: a PC tool, a phone or another board. Bad framing leads to lost bytes and crashes.
How it works
Use a state machine parser: wait for start byte, read length, collect payload, verify CRC, dispatch. Resynchronise on errors, add timeouts, document with a table.
Where it is used
- PC configuration tool
- Module to MCU link
- Sensor network frames
Frame parser state machine
Garbage before the start byte is skipped. A corrupted frame is dropped and the parser resynchronises on the next start byte.
- Version the protocol: put a protocol version in the first message.
- Never trust the length field: check it against your buffer size.
- Use timeouts to abandon half-received frames.
- Prefer little endian for MCU-to-MCU and document the byte order.
- Write the spec as a table before coding: command, direction, payload, response.
Quick quiz
1. Why a start marker?
Parser finds the frame boundary again.
2. Never trust...
It can cause buffer overflows.