
UART DMA idle line detection is the standard way to handle variable-length packets on STM32. Yet it fails silently in ways that waste hours: the HAL_UARTEx_RxEventCallback fires for half-transfer and transfer-complete but never for HAL_UART_RXEVENT_IDLE. Or it works once, then stops. Or enabling the USART IRQ — required for IDLE detection — appears to break all reception.
This article covers the three root causes behind these failures, the exact HAL callback pattern that works, and a complete implementation you can drop into any STM32 project.
Engineers search for this when they see:
HAL_UARTEx_RxEventCallback never called with HAL_UART_RXEVENT_IDLEHAL_UART_RXEVENT_HT and HAL_UART_RXEVENT_TC events firingUSART_ISR but no callback executesThe STM32 HAL’s idle line detection does not run in DMA hardware. It works like this:
IDLE flag in USART_ISRUSARTx_IRQn)USARTx_IRQHandler reads the flag, clears it, and calls HAL_UARTEx_RxEventCallback with HAL_UART_RXEVENT_IDLEIf the global interrupt is disabled, step 3 never happens. The DMA happily fills buffers and fires HT/TC, but the IDLE flag sits in USART_ISR unread.
In CubeMX, this is USARTx > NVIC Settings > Enable USARTx global interrupt. In bare-metal code:
HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);HAL_NVIC_EnableIRQ(USART1_IRQn);
Without this, you get a working DMA stream that never tells you when a packet ends.
CubeMX generates MX_USART1_UART_Init() which calls HAL_UART_Init(). The HAL init function enables the UART peripheral but does not enable the NVIC interrupt by default. Many engineers assume the HAL handles everything. The DMA callbacks (HT, TC) work because they’re DMA interrupts, not UART interrupts. The IDLE callback is a UART interrupt. This asymmetry is the trap.
// Check if USART1 IRQ is actually enabled in NVICbool is_usart1_irq_enabled(void){// USART1_IRQn = 37 on STM32H7/F4, 38 on F1uint32_t irqn = USART1_IRQn;return (NVIC->ISER[irqn / 32] & (1U << (irqn % 32))) != 0;}// Call this after MX_USART1_UART_Init() to confirmassert(is_usart1_irq_enabled());
The USART1 IRQ number varies across STM32 families, which matters when porting code:
| Series | USART1_IRQn | NVIC Priority Bits |
|---|---|---|
| STM32F1 | 37 | 4 bits (16 levels) |
| STM32F4 | 37 | 4 bits |
| STM32F7 | 37 | 4 bits |
| STM32H7 | 37 | 4 bits |
| STM32L4 | 37 | 4 bits |
| STM32G0 | 27 | 2 bits (4 levels) |
| STM32G4 | 37 | 4 bits |
Always verify the IRQ number in the device header file (stm32xxxx.h) rather than hardcoding.
This is the silent killer. Your peripheral sends data during MCU boot. The UART receives garbage before HAL_UART_Init completes. This sets noise error (NE), framing error (FE), or overrun error (ORE) flags.
By default, the HAL does not clear these automatically. Once an error flag is set:
HAL_UARTEx_RxEventCallback stops being called entirelyThe fix is mandatory: implement HAL_UART_ErrorCallback to clear errors and re-arm reception.
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart){if (huart->Instance == USART1) {// Clear all error flags__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF | UART_CLEAR_FEF | UART_CLEAR_OREF | UART_CLEAR_PEF);// Re-arm DMA reception immediatelyif (HAL_UARTEx_ReceiveToIdle_DMA(huart, huart->pRxBuffPtr, huart->RxXferSize) != HAL_OK) {Error_Handler();}}}
This callback fires before the RxEventCallback when errors occur. Without it, the first error permanently disables idle detection.
Consider this timeline:
HAL_UART_Init() runs (~1-2ms)USART_ISRHAL_UARTEx_ReceiveToIdle_DMA() starts DMAUSART1_IRQHandler runs, sees error flags and IDLEThe fix in HAL_UART_ErrorCallback clears the error state so subsequent interrupts process normally.
Each error flag has specific behavior:
The ORE flag is the most dangerous for idle detection because it halts the receiver state machine. Clearing it requires reading USART_RDR after clearing the flag.
HAL_UART_Receive_DMA (normal mode) stops after one buffer fills. For variable-length packets, you don’t know the size upfront. If a 200-byte packet arrives in a 1024-byte buffer, normal mode waits for 824 more bytes — forever.
Circular mode is the only correct choice. The DMA wraps automatically. The IDLE event tells you “packet ended here.” The HT/TC events tell you “buffer wrapping, process what you have.”
// Correct initialization sequencevoid UART1_Init(void){huart1.Instance = USART1;huart1.Init.BaudRate = 1000000;huart1.Init.WordLength = UART_WORDLENGTH_8B;huart1.Init.StopBits = UART_STOPBITS_1;huart1.Init.Parity = UART_PARITY_NONE;huart1.Init.Mode = UART_MODE_TX_RX;huart1.Init.HwFlowCtl = UART_HWCONTROL_NONE;huart1.Init.OverSampling = UART_OVERSAMPLING_16;HAL_UART_Init(&huart1);// Enable IDLE interrupt (HAL does this in ReceiveToIdle_DMA)__HAL_UART_ENABLE_IT(&huart1, UART_IT_IDLE);// Start circular DMA with idle detectionHAL_UARTEx_ReceiveToIdle_DMA(&huart1, rx_buffer, RX_BUFFER_SIZE);// Disable half-transfer interrupt if you only want IDLE + TC__HAL_DMA_DISABLE_IT(huart1.hdmarx, DMA_IT_HT);}
NORMAL MODE (wrong for variable packets):+--------+--------+--------+--------+--------+--------+--------+--------+| Pkt 1 | 200B | | | | | | || (200B) | | 824B | WAIT | FOREVER |+--------+--------+--------+--------+--------+--------+--------+--------+0 1024^ DMA stops here, no more callbacks until buffer fills completelyCIRCULAR MODE (correct):+--------+--------+--------+--------+--------+--------+--------+--------+| Pkt 1 | IDLE | Pkt 2 | IDLE | Pkt 3 | WRAP | Pkt 4 | IDLE || (200B) | event | (150B) | event | (400B) | (TC) | (300B) | event |+--------+--------+--------+--------+--------+--------+--------+--------+0 1024^ DMA wraps, continues writing from 0
Choose buffer size based on your maximum expected packet rate and processing latency:
| Max Packet Size | Max Packet Rate | Min Buffer Size | Recommended |
|---|---|---|---|
| 256 bytes | 100 Hz | 512 bytes | 1024 bytes |
| 512 bytes | 50 Hz | 1024 bytes | 2048 bytes |
| 1024 bytes | 20 Hz | 2048 bytes | 4096 bytes |
Rule: buffer should hold at least 2-4 max packets to absorb processing delays.
Here is a production-ready module for variable-length UART packets using DMA idle detection.
/* uart_idle_dma.h */#ifndef UART_IDLE_DMA_H#define UART_IDLE_DMA_H#include "stm32h7xx_hal.h"#define UART_IDLE_RX_BUF_SIZE 1024#define UART_IDLE_MAX_PACKETS 16typedef struct {uint8_t data[UART_IDLE_RX_BUF_SIZE];uint16_t len;bool ready;} uart_packet_t;typedef struct {UART_HandleTypeDef *huart;uint8_t rx_buf[UART_IDLE_RX_BUF_SIZE];uart_packet_t packets[UART_IDLE_MAX_PACKETS];volatile uint8_t head, tail;volatile uint16_t last_pos;} uart_idle_dma_t;void uart_idle_dma_init(uart_idle_dma_t *ctx, UART_HandleTypeDef *huart);bool uart_idle_dma_get_packet(uart_idle_dma_t *ctx, uint8_t *out_buf, uint16_t *out_len);void uart_idle_dma_process(uart_idle_dma_t *ctx);#endif
/* uart_idle_dma.c */#include "uart_idle_dma.h"#include <string.h>void uart_idle_dma_init(uart_idle_dma_t *ctx, UART_HandleTypeDef *huart){memset(ctx, 0, sizeof(*ctx));ctx->huart = huart;ctx->last_pos = 0;// Enable USART global interrupt (CRITICAL)HAL_NVIC_SetPriority(USART1_IRQn, 5, 0);HAL_NVIC_EnableIRQ(USART1_IRQn);// Start circular DMA with idle detectionHAL_UARTEx_ReceiveToIdle_DMA(huart, ctx->rx_buf, UART_IDLE_RX_BUF_SIZE);// Optional: disable HT interrupt to reduce ISR load__HAL_DMA_DISABLE_IT(huart->hdmarx, DMA_IT_HT);}void uart_idle_dma_process(uart_idle_dma_t *ctx){// Called from main loop or task -- processes completed packets// Actual copy happens in RxEventCallback (ISR context)// This function just manages the ring buffer if needed}bool uart_idle_dma_get_packet(uart_idle_dma_t *ctx, uint8_t *out_buf, uint16_t *out_len){if (ctx->head == ctx->tail) {return false; // No packets ready}uart_packet_t *pkt = &ctx->packets[ctx->tail];memcpy(out_buf, pkt->data, pkt->len);*out_len = pkt->len;pkt->ready = false;ctx->tail = (ctx->tail + 1) % UART_IDLE_MAX_PACKETS;return true;}/* HAL CALLBACKS -- WEAK OVERRIDES IN USER CODE */void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){extern uart_idle_dma_t uart1_ctx; // Your global instanceif (huart->Instance != USART1) return;uint16_t event_type = HAL_UARTEx_GetRxEventType(huart);uint16_t start = uart1_ctx.last_pos;uint16_t len = 0;if (event_type == HAL_UART_RXEVENT_IDLE) {// Variable packet ended -- Size is bytes since last eventif (Size >= start) {len = Size - start;} else {len = (UART_IDLE_RX_BUF_SIZE - start) + Size; // Wrapped}} else if (event_type == HAL_UART_RXEVENT_TC) {// Buffer wrapped -- process from last_pos to endlen = UART_IDLE_RX_BUF_SIZE - start;} else {return; // HT event -- ignore or handle separately}if (len == 0 || len > UART_IDLE_RX_BUF_SIZE) return;// Copy to packet bufferuint8_t next_head = (uart1_ctx.head + 1) % UART_IDLE_MAX_PACKETS;if (next_head != uart1_ctx.tail) { // Buffer not fulluart_packet_t *pkt = &uart1_ctx.packets[uart1_ctx.head];if (start + len <= UART_IDLE_RX_BUF_SIZE) {memcpy(pkt->data, &uart1_ctx.rx_buf[start], len);} else {// Wrapped packet -- copy in two partsuint16_t first = UART_IDLE_RX_BUF_SIZE - start;memcpy(pkt->data, &uart1_ctx.rx_buf[start], first);memcpy(&pkt->data[first], uart1_ctx.rx_buf, len - first);}pkt->len = len;pkt->ready = true;uart1_ctx.head = next_head;}// Else: packet dropped -- handle overflow in your appuart1_ctx.last_pos = Size;}void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart){if (huart->Instance != USART1) return;// Clear all error flags__HAL_UART_CLEAR_FLAG(huart, UART_CLEAR_NEF | UART_CLEAR_FEF |UART_CLEAR_OREF | UART_CLEAR_PEF);// Re-arm DMA receptionextern uart_idle_dma_t uart1_ctx;HAL_UARTEx_ReceiveToIdle_DMA(huart, uart1_ctx.rx_buf, UART_IDLE_RX_BUF_SIZE);uart1_ctx.last_pos = 0;}
// FreeRTOS task that processes UART packetsvoid uart_process_task(void *argument){uart_idle_dma_t *ctx = (uart_idle_dma_t *)argument;uint8_t pkt_buf[UART_IDLE_RX_BUF_SIZE];uint16_t pkt_len;for (;;) {if (uart_idle_dma_get_packet(ctx, pkt_buf, &pkt_len)) {// Process packet -- e.g., parse protocol, push to queueprotocol_parse(pkt_buf, pkt_len);} else {// No packets, yield or wait for notificationulTaskNotifyTake(pdTRUE, pdMS_TO_TICKS(10));}}}// In RxEventCallback, notify task when packet readyvoid HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){// ... existing packet copy logic ...// Notify processing taskBaseType_t higher_priority = pdFALSE;vTaskNotifyGiveFromISR(uart_task_handle, &higher_priority);portYIELD_FROM_ISR(higher_priority);}
Zephyr’s UART async API with uart_rx_enable and uart_callback_set provides similar functionality:
// Zephyr UART async with idle detectionstatic void uart_cb(const struct device *dev, struct uart_event *evt, void *user_data){switch (evt->type) {case UART_RX_RDY:// Data received, check if idle timeout occurredif (evt->data.rx.len > 0) {k_msgq_put(&uart_msgq, &evt->data.rx, K_NO_WAIT);}break;case UART_RX_IDLE:// Idle timeout -- packet completek_msgq_put(&uart_msgq, &evt->data.rx, K_NO_WAIT);break;case UART_RX_DISABLED:// Re-enable receptionuart_rx_enable(dev, rx_buf, sizeof(rx_buf), UART_WAIT_FOR_IDLE);break;default:break;}}
For ultra-low latency requirements, double buffering eliminates the memcpy in the RxEventCallback. Two buffers ping-pong: DMA fills buffer A while CPU processes buffer B, then swap.
// Double buffer setup#define DB_BUF_SIZE 512uint8_t db_buf_a[DB_BUF_SIZE];uint8_t db_buf_b[DB_BUF_SIZE];volatile uint8_t *active_buf = db_buf_a;volatile uint8_t *next_buf = db_buf_b;void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size){if (huart->Instance != USART1) return;// Swap buffers atomicallyuint8_t *filled_buf = (uint8_t *)active_buf;active_buf = next_buf;next_buf = filled_buf;// Reconfigure DMA for next buffer (circular not used here)HAL_UARTEx_ReceiveToIdle_DMA(huart, (uint8_t *)active_buf, DB_BUF_SIZE);// Process filled_buf in task contextk_msgq_put(&uart_msgq, &filled_buf, K_NO_WAIT);}
Trade-off: double buffering uses 2x RAM but zero-copy. Circular buffer with memcpy is simpler and uses less RAM. Choose based on your constraints.
+------------------------------------------------------------------+| UART IDLE DMA EVENT FLOW |+------------------------------------------------------------------+| || PERIPHERAL UART HW DMA CALLBACK || ========= ======== === ======== || || [Packet 1] || ~~~~~~~~> IDLE detected ----> USART_IRQn ----> RxEventCb || (45ms gap) (flag set) (fires) (IDLE, len) || || [Packet 2] || ~~~~~~~~~~~~> Buffer full ----> DMA TC IRQ ----> RxEventCb || (large) (wrap) (fires) (TC, len) || || [Error during init] || ~~~~~> Noise/Overrun ----> USART_IRQn ----> ErrorCb || (boot) (flags set) (fires) (re-arm DMA) || |+------------------------------------------------------------------++------------------------------------------------------------------+| CIRCULAR BUFFER STATE MACHINE |+------------------------------------------------------------------+| || rx_buf[1024] -- circular, DMA writes continuously || || last_pos=0 || |---- Packet 1 (200B) ----| IDLE |-- Packet 2 (150B) --| || 0 200 200 350 || ^ || | || RxEventCb(IDLE, Size=200) -> copy [0:200], last_pos=200 || RxEventCb(IDLE, Size=350) -> copy [200:350], last_pos=350 || || Buffer wrap (TC): || |--- Pkt 3 (400B) ---|--- Pkt 4 (300B) ---|--wrap-->| Pkt 5...| || 0 400 700 1024 0 || || RxEventCb(TC, Size=1024) -> copy [350:1024], last_pos=0 || RxEventCb(IDLE, Size=200) -> copy [0:200], last_pos=200 || |+------------------------------------------------------------------+
// In debugger, check NVIC_ISER register// USART1_IRQn = 37 on STM32H7, 37 on F4, 38 on F1// Bit should be set: (NVIC->ISER[37/32] & (1 << (37%32))) != 0
// In RxEventCallback, add debug:if (event_type == HAL_UART_RXEVENT_IDLE) {// Check ISR directlyuint32_t isr = huart->Instance->ISR;assert(isr & USART_ISR_IDLE); // Should be set before HAL clears it}
# Python test script (pySerial)import serial, time, randomser = serial.Serial('/dev/ttyUSB0', 1000000, timeout=0.1)for _ in range(1000):size = random.randint(10, 500)data = bytes([random.randint(0, 255) for _ in range(size)])ser.write(data)time.sleep(0.05) # 50ms idle gap -- must trigger IDLE# Verify MCU echoes back correct lengthresp = ser.read(4)assert len(resp) == 4
Power on the peripheral before the MCU. Let it send data during boot. Verify:
HAL_UART_ErrorCallback firesSend packets faster than the processing task can handle. Verify:
On STM32H7 with multiple UARTs active, verify no cross-interference:
Run the system for 24+ hours with continuous traffic:
| Symptom | Likely Cause | Fix |
|---|---|---|
| IDLE never fires | USART IRQ disabled | Enable in CubeMX NVIC or HAL_NVIC_EnableIRQ |
| IDLE fires once then stops | Error flags set, no ErrorCallback | Implement HAL_UART_ErrorCallback with re-arm |
| Only HT/TC events | IDLE interrupt not enabled | __HAL_UART_ENABLE_IT(huart, UART_IT_IDLE) |
| Packets truncated at buffer size | Normal DMA mode | Use HAL_UARTEx_ReceiveToIdle_DMA (circular) |
| First packet lost after error | ErrorCallback doesn’t reset last_pos | Set last_pos = 0 in ErrorCallback |
| Callback stack overflow | Heavy processing in ISR | Copy to ring buffer only; process in task |
UART DMA idle line detection fails for three specific reasons:
HAL_UART_ErrorCallbackThe fix is a 50-line callback implementation: enable IRQ, implement ErrorCallback with re-arm, use HAL_UARTEx_ReceiveToIdle_DMA in circular mode. The complete module above handles wrapping, overflow, and error recovery — drop it in, call uart_idle_dma_init, and poll uart_idle_dma_get_packet from your main loop or RTOS task.
This pattern works across STM32F1/F4/F7/H7/L4/G0/G4 series. The HAL API is identical; only the IRQ number and NVIC priority grouping differ.
Quick Links
Legal Stuff





