I've been drilling down on the user's need for an interrupt-driven UART protocol. The Cortex-M platform is key, and I'm homing in on the architectural implications for the design. Right now, I'm focusing on the platform-specific registers and interrupt vector table.
Mapping Out the Layers
I'm now sketching out the architecture's layers. Specifically, I'm focusing on the ISRs and the ring buffers, which I think will be critical. I'm considering different packet structure approaches. The goal is to optimize both interrupt latency and overall throughput. The circular buffers, I think, are the key "glue" for decoupling the application and the hardware.
Architecting the Driver
I'm presently building out the UART driver, carefully considering the ISR routines, especially those handling TX and RX interrupts. The circular buffer structures are central here. I'm focusing on minimizing critical sections and optimizing data transfer between the buffers and the UART hardware. I think I'm now clear about the roles of each of the layers and components.
Refining the Solution
I'm now iterating on the design, focusing on potential bottlenecks. Specifically, I'm considering error handling, such as overrun conditions and full buffer scenarios. I'm also assessing the impact of volatile variables and ensuring atomic operations for shared resources, considering the tradeoffs of performance and complexity. I'm now contemplating the best way to structure the final documentation to make the design straightforward and useful.
Constructing the Solution
I'm now formulating the complete solution based on the requirements. I'm focusing on creating an application, framing the packet protocol, and developing the driver layer, including a state machine. Considering structures and API functions. I am now working on error handling. I plan to refine the code with best practices.
Designing a robust interrupt-driven UART protocol involves three distinct layers:
Data Structure: Circular Buffers (Ring Buffers) to decouple CPU speed from UART baud rate.
Low-Level Driver (LLD): The Interrupt Service Routine (ISR) to move data between hardware and buffers.
Protocol Layer: A Framing Strategy and Finite State Machine (FSM) to decode valid packets.
Below is a complete design guide and C-implementation optimized for ARM Cortex-M.
1. The Frame Format (Packet Structure)
Raw UART data is a stream of bytes. To distinguish instructions from noise, we need a defined packet structure.
Format:[SOF] [CMD] [LEN] [PAYLOAD...] [CRC]
SOF (Start of Frame): A unique byte (e.g., 0xAA) marking the beginning.
CMD (Command): ID of the action to perform.
LEN (Length): Number of bytes in the payload.
PAYLOAD: Data bytes (optional, depends on LEN).
CRC: Checksum (XOR or CRC16) to ensure data integrity.
2. Data Structures: Ring Buffers
We need two FIFO (First-In-First-Out) buffers.
RX Buffer: Host sends data → ISR pushes to RX Buffer → Main Loop processes it.
TX Buffer: Main Loop pushes to TX Buffer → ISR pops and sends to Hardware.
Key Design Rule: Ideally, the ISR should only do two things: push receiving data into a buffer or pop transmitting data to the hardware. It should not process protocol logic.
Note: This uses pseudo-register names (common in STM32/NXP).
c
// This function is called by the NVIC when UART interrupt fires
void UART_IRQHandler(void) {
uint8_t data;
uint32_t status_reg = UART->SR; // Read Status Register
// --- Receive Handling (RX) ---
if (status_reg & UART_FLAG_RXNE) { // RX Not Empty
data = (uint8_t)(UART->DR); // Read Data
RingBuf_Push(&rxQueue, data);
}
// --- Transmit Handling (TX) ---
if (status_reg & UART_FLAG_TXE) { // TX Register Empty
if (RingBuf_Pop(&txQueue, &data)) {
UART->DR = data; // Use HW to send byte
} else {
// No more data to send, disable TX Interrupt
UART->CR1 &= ~UART_IT_TXE;
}
}
}
Send Function (Application Side)
c
void UART_SendBytes(uint8_t *data, uint16_t len) {
for (int i = 0; i < len; i++) {
// Wait if buffer is full (Simple blocking here, or return error)
while (!RingBuf_Push(&txQueue, data[i]));
}
// Provide kickoff: Enable the TX Interrupt to start the ISR chain
__disable_irq(); // Critical section
UART->CR1 |= UART_IT_TXE;
__enable_irq();
}
4. Protocol Logic: Finite State Machine (FSM)
Do not use while() loops to wait for bytes in your main code. This blocks the CPU. Use a State Machine that processes one byte at a time as they become available in the RX Buffer.
c
typedef enum {
STATE_WAIT_SOF,
STATE_GET_CMD,
STATE_GET_LEN,
STATE_GET_PAYLOAD,
STATE_CHECK_CRC
} ProtocolState;
ProtocolState currState = STATE_WAIT_SOF;
Packet_t tempPacket;
uint8_t payloadIndex = 0;
void Process_UART_Stream(void) {
uint8_t byte;
// Process all available bytes in the RX Ring Buffer
while (RingBuf_Pop(&rxQueue, &byte)) {
switch (currState) {
case STATE_WAIT_SOF:
if (byte == UART_SOF) {
currState = STATE_GET_CMD;
}
break;
case STATE_GET_CMD:
tempPacket.cmd = byte;
currState = STATE_GET_LEN;
break;
case STATE_GET_LEN:
tempPacket.len = byte;
if (tempPacket.len > sizeof(tempPacket.payload)) {
// Error: Length too big, reset
currState = STATE_WAIT_SOF;
} else if (tempPacket.len == 0) {
currState = STATE_CHECK_CRC;
} else {
payloadIndex = 0;
currState = STATE_GET_PAYLOAD;
}
break;
case STATE_GET_PAYLOAD:
tempPacket.payload[payloadIndex++] = byte;
if (payloadIndex >= tempPacket.len) {
currState = STATE_CHECK_CRC;
}
break;
case STATE_CHECK_CRC:
uint8_t calcedCRC = Calculate_CRC(tempPacket.cmd, tempPacket.len, tempPacket.payload);
if (byte == calcedCRC) {
// Valid Packet Found! Execute Action.
Execute_Command(&tempPacket);
}
// Reset State regardless of pass/fail
currState = STATE_WAIT_SOF;
break;
}
}
}
5. Integration (Main Loop)
The Cortex-M main loop remains non-blocking. It only processes data when the ISR has filled the buffer.
c
int main(void) {
HAL_Init();
UART_Init(); // Enable UART hardware and NVIC Interrupts
while (1) {
// 1. Check High priority tasks
// 2. Process UART Data
Process_UART_Stream();
// 3. Other Application Logic
// The system effectively multitasks receiving UART data
// and doing other work.
}
}
6. Critical Considerations for Cortex-M
NVIC Priority: Set the UART Interrupt priority reasonably. If it is too low, a high-priority timer interrupt might block it for too long, causing a UART Overrun Error (hardware buffer overflow).
Atomic Access: When modifying rb->head or rb->tail, ensure the operation is atomic. In the UART_SendBytes example, we disabled interrupts __disable_irq() briefly when enabling the TX interrupt bit to prevent race conditions.
DMA (Direct Memory Access): For very high baud rates (>1 Mbps) or large packets, interrupt overhead is too high. In that case, replace the ISR Byte-by-Byte method with DMA Circular Mode.
Error Handling: Monitor UART Error Flags (Framing Error, Noise Error, Overrun Error) in the ISR. If an error occurs, clear the flags and optionally reset the FSM currState = STATE_WAIT_SOF.