The user wants a design for an interrupt-driven UART communication protocol for an ARM Cortex-M microcontroller.
1. Understand the Requirements:
- Target: ARM Cortex-M microcontroller (e.g., STM32, NRF52, SAM D21, etc.). The specific vendor doesn't matter too much for the concept, but the CMSIS standard is a good baseline.
- Interface: UART (Universal Asynchronous Receiver-Transmitter).
- Mechanism: Interrupt-driven (not polling, not DMA yet, though DMA is often the next step).
- Goal: A "communication protocol." This implies not just raw character read/write, but framing, error handling, and perhaps a circular buffer implementation.
2. Key Components of an Interrupt-Driven UART System:
- Hardware Setup: Baud rate, parity, stop bits, enabling the UART peripheral and its clock.
- GPIO Setup: TX/RX pin configuration.
- Interrupt Configuration: Enabling specific UART interrupts (RXNE - Receive Register Not Empty, TXE - Transmit Register Empty) and the NVIC (Nested Vector Interrupt Controller).
- Software Buffers (Circular Buffers/FIFOs): Crucial for decoupling the ISR (Interrupt Service Routine) from the main processing loop. We need one for TX and one for RX.
- The ISR (Interrupt Handler): The core logic. It needs to check flags, read data (clearing the flag), write data (clearing the flag), and handle errors.
- API (Application Programming Interface): Functions for the user to
init, read, write, and available.
- Protocol Layer (Optional but requested): A simple framing mechanism (Start byte, Length, Data, Checksum) to make it a "protocol" rather than just a driver. Let's add a simple packet parser state machine.
3. Structuring the Response:
- Introduction: Briefly explain the benefits (non-blocking, efficient).
- Architecture Overview: Diagram or description of the buffers and data flow.
- Data Structures: Define the Circular Buffer struct.
- Hardware Abstraction (HAL/Low-Level): Since I don't know the specific chip (STM32 vs. NXP), I will use pseudocode or generic CMSIS-style register access, but clarify that users need to adapt this to their HAL (HAL_UART_Receive_IT vs. direct registers). Self-correction: Direct register manipulation is harder to read for beginners. I'll stick to a generic C-style approach that looks like pseudo-HAL or CMSIS but is clear enough to implement.
- Implementation Steps:
- Buffers: The circular buffer implementation.
- Initialization: Setup HW and NVIC.
- The ISR: The critical part.
- Public API:
uart_write, uart_read.
- Protocol Layer: A simple state machine to process the bytes into packets.
- Error Handling: Overrun, Framing, Noise errors.
4. Drafting the Content - Step-by-Step:
-
Circular Buffer: Needs buffer, head, tail, count (optional but helpful). Let's keep it simple: head (write index), tail (read index).
push: write to head, increment head.
pop: read from tail, increment tail.
-
The ISR:
- RX: If RXNE flag is set, read DR (Data Register) and push to RX_Buffer. If buffer full, handle error (drop byte or overwrite old).
- TX: If TXE flag is set:
- If TX_Buffer is not empty, pop byte and write to DR.
- If TX_Buffer is empty, disable the TXE interrupt. This is a common mistake. You don't want the ISR firing constantly asking "Is there data to send?" when there isn't. You only turn it on when you have data to send.
-
The Write Function:
- Disable IRQs (Critical section) to ensure atomic access to the buffer.
- Push data to TX_Buffer.
- Enable TXE interrupt to kickstart transmission.
- Restore IRQs.
-
The Protocol:
- Let's design a simple packet:
[Header][Length][Payload][CRC].
- State Machine:
STATE_WAIT_HEADER, STATE_WAIT_LEN, STATE_PAYLOAD, STATE_CRC.
5. Refining the Code Examples (Mental Sandbox):
- Language: C.
- Style: Clean, commented.
- Hardware specifics: I will assume standard CMSIS register naming (e.g.,
USART1->DR, USART1->SR) or generic function wrappers to keep it broadly applicable.
6. Detailed Design Section:
-
Circular Buffer:
typedef struct {
uint8_t buffer[BUFFER_SIZE];
volatile uint16_t head;
volatile uint16_t tail;
} RingBuffer_t;
Note: volatile is essential here because values change inside ISR.
-
The ISR Logic (The "Secret Sauce"):
- Check
RXNE.
- Check
TXE.
- Crucial Logic: When
uart_write is called, it puts data in the buffer. It then enables the TX interrupt. The ISR pulls from the buffer. When the buffer is empty, the ISR disables its own TX interrupt.
-
Protocol Design:
- Let's define a "Packetizer".
- Every time
uart_getc returns a byte, feed it to the packet parser.
7. Review against constraints:
- "ARM Cortex-M": Mention NVIC priorities.
- "Interrupt-driven": Yes.
- "Protocol": Include the framing logic.
8. Final Polish:
- Add a section on "Best Practices" (Critical sections, DMA mention).
- Ensure the distinction between the Driver (sending bytes) and the Protocol (parsing packets) is clear.
(Self-Correction during drafting): I initially thought about writing specific STM32 HAL code. However, that changes often and is vendor-specific. It is better to write "Generic Pseudo-CMSIS" code but explain what registers to touch, so the user can map it to their specific HAL (like __HAL_UART_ENABLE_IT). I will write the code to be as portable C as possible, using generic structs like UART_Handle.
Let's structure the Protocol part. Just sending bytes isn't a protocol. I will propose a simple "SOF (Start of Frame) + Length + Data + Checksum" structure. This is robust enough for embedded systems.
Plan:
- High-Level Architecture: Driver vs. Protocol.
- The Ring Buffer: The core data structure.
- The Driver (ISR + API): The low-level code.
- The Protocol (State Machine): The logic to parse bytes into meaningful data.
- Critical Implementation Details: Atomic operations.
This looks solid. I will generate the response based on this structure.
This design describes a robust Interrupt-Driven UART communication stack for an ARM Cortex-M microcontroller (e.g., STM32, NRF52, LPC).
The design is split into two layers:
- The Driver Layer: Handles hardware registers and ring buffers (FIFO).
- The Protocol Layer: A simple framing protocol (COBS or Consistent Overhead Byte Stuffing) to ensure data integrity.
1. Architecture Overview
In a bare-metal or RTOS environment, reading bytes one by one inside the main loop is inefficient. We use interrupts to handle the timing-critical UART hardware, pushing bytes into a software buffer (Ring Buffer) for the main application to process at its own pace.
Key Components:
- Hardware FIFO: (If available) Reduces interrupt frequency.
- Ring Buffer: A circular queue to store data between the ISR and the main loop.
- Interrupt Service Routines (ISR):
- RX Not Empty: Triggers when a byte is received.
- TX Empty: Triggers when the UART is ready for the next byte.
- Error: Handles overrun, framing, or noise errors.
2. The Driver Layer (C Code)
This code is generic enough to adapt to STM32 HAL, standard CMSIS, or vendor-specific libraries.
2.1. Data Structures
We define a structure to manage the buffer and a handle for the UART instance.
#include <stdint.h>
#include <stdbool.h>
#include <string.h>
// Buffer Size configuration
#define UART_BUFFER_SIZE 128
// Ring Buffer Structure
typedef struct {
uint8_t buffer[UART_BUFFER_SIZE];
volatile uint16_t head; // Write index (updated by ISR)
volatile uint16_t tail; // Read index (updated by Main Loop)
} RingBuffer_t;
// UART Handle Structure
typedef struct {
// Hardware register pointer (e.g., USART_TypeDef *Instance)
void *Instance;
// Buffers
RingBuffer_t rx_buffer;
RingBuffer_t tx_buffer;
// Transmission State
volatile bool tx_busy;
} UART_Handle_t;
2.2. Buffer Helper Functions
These usually reside in the .c file or as static inline functions.
// Check if buffer is empty
bool RingBuffer_IsEmpty(RingBuffer_t *rb) {
return (rb->head == rb->tail);
}
// Read a byte from buffer
bool RingBuffer_Pop(RingBuffer_t *rb, uint8_t *data) {
if (RingBuffer_IsEmpty(rb)) return false;
*data = rb->buffer[rb->tail];
rb->tail = (rb->tail + 1) % UART_BUFFER_SIZE;
return true;
}
// Write a byte to buffer
bool RingBuffer_Push(RingBuffer_t *rb, uint8_t data) {
uint16_t next_head = (rb->head + 1) % UART_BUFFER_SIZE;
// Check if buffer is full
if (next_head == rb->tail) return false;
rb->buffer[rb->head] = data;
rb->head = next_head;
return true;
}
2.3. The Interrupt Service Routines (ISR)
This is the core logic.
- RX: Store byte immediately.
- TX: Send next byte if available; otherwise, disable the interrupt to stop triggering.
// This function is called inside your specific UARTx_IRQHandler
void UART_Generic_IRQ_Handler(UART_Handle_t *huart) {
// 1. Handle Reception (RXNE Flag)
if (READ_REG(huart->Instance->SR) & UART_FLAG_RXNE) {
uint8_t data = (uint8_t)(READ_REG(huart->Instance->DR) & 0xFF);
// Push to software buffer. If full, data is lost (or handle overflow logic)
RingBuffer_Push(&huart->rx_buffer, data);
}
// 2. Handle Transmission (TXE Flag - Transmit Register Empty)
if (READ_REG(huart->Instance->SR) & UART_FLAG_TXE) {
if (!RingBuffer_IsEmpty(&huart->tx_buffer)) {
// Pop from buffer and send
uint8_t data;
RingBuffer_Pop(&huart->tx_buffer, &data);
WRITE_REG(huart->Instance->DR, data);
} else {
// Buffer empty. Disable TXE interrupt to prevent infinite loop.
// It will be re-enabled when new data is sent.
CLEAR_BIT(huart->Instance->CR1, UART_CR1_TXEIE);
huart->tx_busy = false;
}
}
// 3. Handle Errors (Overrun, Framing, etc.)
// Clear flags or reset peripheral as needed.
}
2.4. Public API
These functions are called by your main application.
// Initialize UART hardware and enable RX Interrupt
void UART_Init(UART_Handle_t *huart) {
// ... Hardware Init (Baud rate, GPIOs) ...
// Enable RX Not Empty Interrupt
SET_BIT(huart->Instance->CR1, UART_CR1_RXNEIE);
// Enable Global UART Interrupt in NVIC
NVIC_EnableIRQ(USART1_IRQn);
}
// Non-blocking Read
uint16_t UART_Read(UART_Handle_t *huart, uint8_t *data, uint16_t len) {
uint16_t count = 0;
while (count < len && RingBuffer_Pop(&huart->rx_buffer, &data[count])) {
count++;
}
return count;
}
// Non-blocking Write
void UART_Write(UART_Handle_t *huart, uint8_t *data, uint16_t len) {
// 1. Push data to TX Buffer
for (int i = 0; i < len; i++) {
RingBuffer_Push(&huart->tx_buffer, data[i]);
}
// 2. Start Transmission if not already busy
// Critical Section: Disable IRQs briefly to avoid race condition
uint32_t primask = __get_PRIMASK();
__disable_irq();
if (!huart->tx_busy) {
huart->tx_busy = true;
// Enable TXE Interrupt (Triggers ISR immediately)
SET_BIT(huart->Instance->CR1, UART_CR1_TXEIE);
}
__set_PRIMASK(primask); // Restore IRQ state
}
3. The Protocol Layer (Framing)
Raw UART streams have no synchronization. If you enable the microcontroller halfway through a message, your data will be misaligned. We need a Protocol.
A recommended approach for embedded systems is Consistent Overhead Byte Stuffing (COBS) combined with a simple packet structure.
Packet Structure
| Start Byte (0x00) | Data (Variable Length) | CRC8 |
|---|
Why 0x00 as Start?
UART lines idle HIGH (logic 1). 0x00 is a distinct break in the pattern. In COBS, 0x00 is strictly used as a delimiter.
How to Process (State Machine)
Do not process packets inside the ISR. Process them in the main() loop.
typedef enum {
STATE_WAIT_START,
STATE_READ_DATA,
STATE_VALIDATE
} ProtocolState_t;
void ProcessIncomingBytes(UART_Handle_t *huart) {
uint8_t byte;
// Drain the buffer completely
while (RingBuffer_Pop(&huart->rx_buffer, &byte)) {
switch(current_state) {
case STATE_WAIT_START:
if (byte == 0x00) {
rx_idx = 0;
current_state = STATE_READ_DATA;
}
break;
case STATE_READ_DATA:
if (byte == 0x00) {
// End of packet found
current_state = STATE_VALIDATE;
} else {
// Store byte (ensure buffer overflow protection)
if (rx_idx < MAX_PACKET_SIZE) {
temp_buffer[rx_idx++] = byte;
}
}
break;
case STATE_VALIDATE:
// Decode COBS here...
// Check CRC here...
// If valid, notify application
// OnMessageReceived(decoded_payload);
// Reset for next packet
current_state = STATE_WAIT_START;
break;
}
}
}
4. System Integration Strategy
- Startup: In
main(), call UART_Init().
- Sending: Call
UART_Write() anytime. It returns immediately.
- Receiving: Inside your
while(1) loop, call ProcessIncomingBytes().
- This "Pull" method ensures the main loop isn't blocked.
- If the main loop is slow, increase
UART_BUFFER_SIZE.
5. Advanced Optimization (DMA)
If your Cortex-M supports it, replace the TX Interrupt with DMA (Direct Memory Access).
- TX DMA: You give the DMA controller the pointer to your ring buffer tail. The DMA sends the data without CPU intervention. You only get an interrupt when the block is finished (Half-Transfer or Transfer-Complete).
- RX DMA: Use "Circular DMA". The DMA writes continuously to a buffer. You check the DMA counter (CNDTR) against your software pointer to see how many new bytes arrived. This reduces CPU load to nearly zero.