Designing UART Protocol
The user is asking for an interrupt-driven UART communication protocol for an ARM Cortex-M microcontroller. They likely want a detailed design, specifically about hardware abstraction, ring buffers, interrupts, framing, and error handling. Since this is about embedded systems, I should consider providing code examples in C along with a protocol description, ensuring it's vendor-neutral and covering generic Cortex-M options like STM32 and NXP. I want to balance detail and conciseness, leaning towards moderately detailed without being overly elaborate.Designing UART Communication Protocol
I'm planning to create a typical full-duplex, asynchronous serial communication protocol, like 115200 baud, with 8 data bits, no parity, and 1 stop bit. The design will incorporate TX and RX ring buffers, with interrupts triggered by RXNE and errors for receiving, while TXE and TC will handle sending. Mutual exclusion and concurrency must be considered, as well as buffer overflow strategies. I should also provide conceptual explanations and examples, including pseudocode for initialization and interface functions like uart_init(), uart_write(), and uart_read(). This ensures a comprehensive design that meets user needs.Designing Interrupt-Driven Protocol
I’ll consider both DMA and interrupt-based approaches, but since the user specifically requested an "interrupt-driven" design, I’ll focus on that. Handling concurrency is essential, as the main code will be running a superloop or RTOS tasks while the ISR interacts through ring buffers, so marking variables as volatile is necessary. The protocol will involve defining a simple packet format with start-of-frame, length, type, payload, and CRC16. I'll outline the high-level design, driver architecture, and provide C-like implementation steps, using general register names without relying on external libraries to maintain vendor neutrality.Sketching UART Protocol Design
I'll start by outlining the UART communication protocol, focusing on the main goals. First, I'll cover the UART hardware configuration and the necessary data structures, specifically ring buffers. I'll detail the interrupt service routines for transmitting, receiving, and handling errors. The API will include functions like uart_init, uart_write, uart_read, and callbacks. For the application-level framing protocol, I'll ensure it’s reliable over noisy lines and supports commands. I'll go with a frame format that includes a start-of-frame byte, length, message type, payload, and a CRC16 for error detection, keeping the design adaptable and straightforward.Designing the UART Protocol with Escape Mechanism
I need to handle special bytes like 0x7E and possibly 0x7D in the payload. A simple escape scheme will work where 0x7E is encoded as 0x7D 0x5E for ease of parsing, similar to the PPP method. The RX state machine will include states for idle and receiving length, along with CRC verification. I'll create a function to handle both receiving and sending, ensuring the ISR only manipulates the ring buffer. For robustness, error handling and timeouts should be included. I’ll also provide a ring buffer structure and push/pop functionality, ensuring atomic access where needed. Below is a complete, generic design for an interrupt‑driven UART communication protocol on an ARM Cortex‑M microcontroller, split into:
- Hardware/UART driver design (interrupt‑driven, ring buffers)
- A simple packet‑based protocol on top of that (framing, checksum, parsing)
Vendor-specific details (e.g., STM32, NXP, etc.) can be filled in based on your MCU, but the structure stays the same.
1. Goals and architecture
Goals
- Non‑blocking transmit and receive
- Minimal work in interrupts (fast ISRs)
- Safe concurrency between main code and ISRs
- Packet‑based protocol (start‑of‑frame, length, checksum, etc.)
- Robust to line errors and partial packets
Architecture
- Low-level UART driver:
- TX and RX circular (ring) buffers
- RX interrupt on RXNE (receive not empty)
- TX interrupt on TXE (transmit data register empty)
- Optional error interrupts (overrun, framing, parity)
- Higher-level protocol layer:
- Frames:
[SOF][LEN][TYPE][PAYLOAD...][CRC]
- Byte‑stuffing so SOF/ESC bytes can appear in payload
- RX state machine that reconstructs packets
- APIs to send and receive framed messages
2. UART driver design (interrupt‑driven)
2.1 Data structures
Use two ring buffers for TX and RX. Sizes must be powers of 2 if you want cheap wrapping with bitmasking, but that’s optional.
#include <stdint.h>
#include <stdbool.h>
#define UART_RX_BUFFER_SIZE 256
#define UART_TX_BUFFER_SIZE 256
typedef struct {
volatile uint16_t head;
volatile uint16_t tail;
uint8_t buf[UART_RX_BUFFER_SIZE];
} ring_buffer_rx_t;
typedef struct {
volatile uint16_t head;
volatile uint16_t tail;
uint8_t buf[UART_TX_BUFFER_SIZE];
} ring_buffer_tx_t;
static ring_buffer_rx_t uart_rx_buffer = {0};
static ring_buffer_tx_t uart_tx_buffer = {0};
Ring buffer operations (single-producer/single-consumer, no locks needed if used consistently: main <-> ISR):
static bool rb_rx_is_empty(void) {
return uart_rx_buffer.head == uart_rx_buffer.tail;
}
static bool rb_rx_is_full(void) {
return ((uart_rx_buffer.head + 1) % UART_RX_BUFFER_SIZE) == uart_rx_buffer.tail;
}
static void rb_rx_push(uint8_t byte) {
uint16_t next = (uart_rx_buffer.head + 1) % UART_RX_BUFFER_SIZE;
if (next == uart_rx_buffer.tail) {
// Overflow: drop byte or overwrite (design choice)
// For now, just drop.
return;
}
uart_rx_buffer.buf[uart_rx_buffer.head] = byte;
uart_rx_buffer.head = next;
}
static bool rb_rx_pop(uint8_t *byte) {
if (rb_rx_is_empty()) return false;
*byte = uart_rx_buffer.buf[uart_rx_buffer.tail];
uart_rx_buffer.tail = (uart_rx_buffer.tail + 1) % UART_RX_BUFFER_SIZE;
return true;
}
// Same idea for TX:
static bool rb_tx_is_empty(void) {
return uart_tx_buffer.head == uart_tx_buffer.tail;
}
static bool rb_tx_is_full(void) {
return ((uart_tx_buffer.head + 1) % UART_TX_BUFFER_SIZE) == uart_tx_buffer.tail;
}
static bool rb_tx_push(uint8_t byte) {
uint16_t next = (uart_tx_buffer.head + 1) % UART_TX_BUFFER_SIZE;
if (next == uart_tx_buffer.tail) {
// TX buffer full: caller must handle (e.g., block or return error)
return false;
}
uart_tx_buffer.buf[uart_tx_buffer.head] = byte;
uart_tx_buffer.head = next;
return true;
}
static bool rb_tx_pop(uint8_t *byte) {
if (rb_tx_is_empty()) return false;
*byte = uart_tx_buffer.buf[uart_tx_buffer.tail];
uart_tx_buffer.tail = (uart_tx_buffer.tail + 1) % UART_TX_BUFFER_SIZE;
return true;
}
2.2 UART initialization
Use CMSIS-style pseudo-code; replace USARTx and clock settings with those for your chip.
#include "stm32f4xx.h" // or your device header
void uart_init(uint32_t baudrate) {
// 1. Enable peripheral clocks (MCU-specific)
// Example for STM32F4:
// RCC->APB2ENR |= RCC_APB2ENR_USART1EN;
// RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
// 2. Configure TX/RX pins for alternate function (MCU-specific)
// 3. Configure UART parameters: baud, 8N1, etc.
// Example (simplified):
USART1->CR1 = 0; // Disable to configure
USART1->BRR = SystemCoreClock / baudrate; // Very simplified
USART1->CR1 = USART_CR1_TE | USART_CR1_RE | USART_CR1_RXNEIE;
// Optional: Enable error interrupts
// USART1->CR3 |= USART_CR3_EIE;
// 4. Enable UART
USART1->CR1 |= USART_CR1_UE;
// 5. Enable interrupts in NVIC
NVIC_SetPriority(USART1_IRQn, 5);
NVIC_EnableIRQ(USART1_IRQn);
}
Key flags (names vary by vendor):
TE = Transmitter enable
RE = Receiver enable
RXNEIE = RX not empty interrupt enable
TXEIE = TX data register empty interrupt enable (we’ll enable/disable this dynamically)
2.3 UART ISR (RX and TX)
Keep the ISR short: just move bytes between UART register and ring buffers, and record errors.
void USART1_IRQHandler(void) {
uint32_t sr = USART1->SR; // Status register
uint8_t data;
// Handle RX
if (sr & USART_SR_RXNE) {
data = (uint8_t)USART1->DR; // Read clears RXNE
rb_rx_push(data);
}
// Handle errors (optional but recommended)
if (sr & (USART_SR_ORE | USART_SR_FE | USART_SR_PE)) {
// Read DR to clear ORE, etc.
(void)USART1->DR;
// Optionally count errors / flag them
}
// Handle TX
if ((sr & USART_SR_TXE) && (USART1->CR1 & USART_CR1_TXEIE)) {
if (rb_tx_pop(&data)) {
USART1->DR = data;
} else {
// Nothing left to send; disable TXE interrupt
USART1->CR1 &= ~USART_CR1_TXEIE;
}
}
}
2.4 Non-blocking UART API
A simple API where:
uart_write() queues data in TX buffer and triggers TXE interrupt.
uart_read() retrieves bytes from RX buffer.
- Higher layers (the protocol) use these.
bool uart_write_byte(uint8_t byte) {
bool ok = rb_tx_push(byte);
if (!ok) return false;
// Ensure TXE interrupt is enabled so bytes get sent
USART1->CR1 |= USART_CR1_TXEIE;
return true;
}
bool uart_write(const uint8_t *data, uint16_t len) {
for (uint16_t i = 0; i < len; i++) {
if (!uart_write_byte(data[i])) {
// Buffer full; caller decides what to do
return false;
}
}
return true;
}
bool uart_read_byte(uint8_t *byte) {
return rb_rx_pop(byte);
}
This gives you a fully interrupt‑driven, non‑blocking UART driver.
3. Packet protocol on top of UART
Now define a simple, robust, byte‑oriented protocol on top:
3.1 Frame format
Define two special bytes:
SOF = 0x7E (start of frame)
ESC = 0x7D (escape byte for stuffing)
Frame (on the wire), before byte-stuffing:
+------+-----+------+-----------+--------+
| SOF | LEN | TYPE | PAYLOAD | CRC16 |
+------+-----+------+-----------+--------+
1B 1B 1B LEN-3 bytes 2B
LEN = total length of [LEN, TYPE, PAYLOAD, CRC16] (so LEN = 1 + 1 + payload_len + 2)
TYPE = message type (command ID, etc.)
PAYLOAD = 0..(MAX) bytes
CRC16 = CRC-16-CCITT over [LEN, TYPE, PAYLOAD]
3.2 Byte stuffing
To ensure SOF and ESC do not appear inside a frame (outside the first SOF), use a simple escape scheme:
- When sending:
- If a byte equals
SOF (0x7E) or ESC (0x7D), send:
ESC followed by byte ^ 0x20
- Else: send byte as-is.
- On receive:
- When you see
ESC, read the next byte and decode as (next ^ 0x20).
This avoids ambiguity in frame boundaries and allows binary payload.
3.3 CRC16 function
Use CRC-16-CCITT (poly 0x1021, initial value 0xFFFF, no reflection, no XOR out). Example:
static uint16_t crc16_ccitt(const uint8_t *data, uint16_t len) {
uint16_t crc = 0xFFFF;
for (uint16_t i = 0; i < len; i++) {
crc ^= (uint16_t)data[i] << 8;
for (uint8_t j = 0; j < 8; j++) {
if (crc & 0x8000) crc = (crc << 1) ^ 0x1021;
else crc <<= 1;
}
}
return crc;
}
4. Transmit side: building and sending a frame
High-level API:
bool proto_send(uint8_t type, const uint8_t *payload, uint8_t payload_len);
Implementation:
#define SOF 0x7E
#define ESC 0x7D
bool proto_send(uint8_t type, const uint8_t *payload, uint8_t payload_len) {
// Build unstuffed frame in a temp buffer
uint8_t buf[1 + 1 + 1 + 255 + 2]; // [LEN][TYPE][PAYLOAD][CRC16], max payload 255
uint16_t idx = 0;
uint8_t len = 1 + 1 + payload_len + 2; // [LEN][TYPE][PAYLOAD][CRC16]
buf[idx++] = len;
buf[idx++] = type;
for (uint8_t i = 0; i < payload_len; i++) {
buf[idx++] = payload[i];
}
uint16_t crc = crc16_ccitt(buf, idx);
buf[idx++] = (uint8_t)(crc >> 8);
buf[idx++] = (uint8_t)(crc & 0xFF);
// Now send: SOF + stuffed(buf)
if (!uart_write_byte(SOF)) return false;
for (uint16_t i = 0; i < idx; i++) {
uint8_t b = buf[i];
if (b == SOF || b == ESC) {
if (!uart_write_byte(ESC)) return false;
if (!uart_write_byte(b ^ 0x20)) return false;
} else {
if (!uart_write_byte(b)) return false;
}
}
return true;
}
If TX buffer can fill, the function may return false; you can:
- Retry later, or
- Block until space is available (e.g., polling until
rb_tx_is_full() is false), depending on system requirements.
5. Receive side: parsing frames with a state machine
Design a parser that:
- Runs in the main loop (or a task), not in the ISR
- Pulls bytes from the UART RX ring buffer (
uart_read_byte())
- Manages byte-stuffing and frame assembly
- Verifies CRC and dispatches complete frames
5.1 Parser state machine
States:
typedef enum {
RX_STATE_IDLE,
RX_STATE_IN_FRAME,
RX_STATE_ESCAPED
} rx_state_t;
Parser context:
#define PROTO_MAX_FRAME_SIZE (1 + 1 + 255 + 2) // LEN+TYPE+PAYLOAD+CRC
typedef struct {
rx_state_t state;
uint8_t frame[PROTO_MAX_FRAME_SIZE];
uint16_t pos; // position in frame[] (for LEN+TYPE+PAYLOAD+CRC)
uint8_t expected_len; // value of LEN byte
bool len_received;
} proto_rx_ctx_t;
static proto_rx_ctx_t rx_ctx = { .state = RX_STATE_IDLE };
5.2 Parsing function (called from main loop)
static void proto_reset_rx(void) {
rx_ctx.state = RX_STATE_IDLE;
rx_ctx.pos = 0;
rx_ctx.len_received = false;
rx_ctx.expected_len = 0;
}
static void proto_handle_complete_frame(const uint8_t *frame, uint8_t len) {
// frame[0] = LEN, frame[1] = TYPE, frame[2..] = PAYLOAD + CRC16
uint8_t frame_len = frame[0];
uint8_t type = frame[1];
uint8_t payload_len = frame_len - 1 - 2; // TYPE (1) + CRC16 (2)
const uint8_t *payload = &frame[2];
const uint8_t *crc_ptr = &frame[2 + payload_len];
uint16_t crc_rx = (crc_ptr[0] << 8) | crc_ptr[1];
uint16_t crc_calc = crc16_ccitt(frame, frame_len - 2); // exclude CRC
if (crc_rx != crc_calc) {
// CRC error: discard
return;
}
// At this point: frame is valid, deliver to application
// e.g., switch(type) { ... }
}
void proto_process_rx(void) {
uint8_t byte;
while (uart_read_byte(&byte)) {
switch (rx_ctx.state) {
case RX_STATE_IDLE:
if (byte == SOF) {
rx_ctx.state = RX_STATE_IN_FRAME;
rx_ctx.pos = 0;
rx_ctx.len_received = false;
}
break;
case RX_STATE_IN_FRAME:
if (byte == SOF) {
// Start of a new frame; reset current
rx_ctx.pos = 0;
rx_ctx.len_received = false;
} else if (byte == ESC) {
rx_ctx.state = RX_STATE_ESCAPED;
} else {
// Normal byte
if (!rx_ctx.len_received) {
rx_ctx.expected_len = byte;
rx_ctx.len_received = true;
rx_ctx.frame[rx_ctx.pos++] = byte;
if (rx_ctx.expected_len > PROTO_MAX_FRAME_SIZE) {
// Invalid length, reset
proto_reset_rx();
}
} else {
// Already got LEN, store subsequent bytes
if (rx_ctx.pos < rx_ctx.expected_len) {
rx_ctx.frame[rx_ctx.pos++] = byte;
if (rx_ctx.pos == rx_ctx.expected_len) {
// Complete frame received
proto_handle_complete_frame(rx_ctx.frame, rx_ctx.expected_len);
proto_reset_rx();
}
} else {
// Overflow, reset
proto_reset_rx();
}
}
}
break;
case RX_STATE_ESCAPED:
// Interpret escaped byte
byte ^= 0x20;
// Now treat 'byte' as normal data in IN_FRAME state
rx_ctx.state = RX_STATE_IN_FRAME;
if (!rx_ctx.len_received) {
rx_ctx.expected_len = byte;
rx_ctx.len_received = true;
rx_ctx.frame[rx_ctx.pos++] = byte;
if (rx_ctx.expected_len > PROTO_MAX_FRAME_SIZE) {
proto_reset_rx();
}
} else {
if (rx_ctx.pos < rx_ctx.expected_len) {
rx_ctx.frame[rx_ctx.pos++] = byte;
if (rx_ctx.pos == rx_ctx.expected_len) {
proto_handle_complete_frame(rx_ctx.frame, rx_ctx.expected_len);
proto_reset_rx();
}
} else {
proto_reset_rx();
}
}
break;
}
}
}
Call proto_process_rx() regularly (e.g., from the main loop or a periodic task). It pulls all pending UART bytes and feeds them into the state machine.
6. Integrating everything
Main program (superloop example):
int main(void) {
SystemInit();
uart_init(115200);
// Application init...
while (1) {
// Process received bytes and handle complete frames
proto_process_rx();
// Application logic...
// Example: periodically send a heartbeat
// static uint32_t last = 0;
// if (millis() - last > 1000) {
// uint8_t payload[] = { 0x01 }; // heartbeat code
// proto_send(0x10, payload, sizeof(payload));
// last = millis();
// }
}
}
In an RTOS, you’d typically:
- Let the UART ISR fill the RX buffer
- Have a task that blocks on a semaphore/queue signaled by the ISR or polls
uart_read_byte()
- Run
proto_process_rx() in that task context
- Use
proto_send() from tasks, possibly protected with a mutex if shared across tasks
7. Summary of the design
- Interrupt-driven UART driver:
- RXNE and TXE interrupts
- RX/TX ring buffers
- Non-blocking
uart_write() / uart_read()
- Protocol layer:
- Framed packets with SOF + LEN + TYPE + PAYLOAD + CRC16
- Byte stuffing (ESC) for binary-transparent framing
- RX state machine in main/task context
- Simple
proto_send() to send framed messages
This structure is portable to any ARM Cortex‑M family; you mainly adapt the UART register names, clock setup, and interrupt vector names to your specific MCU.
If you share which Cortex‑M family or vendor you’re using (e.g., STM32F4, LPC, Kinetis), I can show the same design with concrete register configurations for that chip.