STM32 UART Reception with DMA and IDLE Line Detection: Variable-Length Data Without Losing Bytes
Receiving a fixed number of bytes over UART is easy. Real devices rarely send fixed-length data: GNSS modules emit NMEA sentences of varying length, modems answer with AT responses you cannot predict, and custom protocols mix short ACKs with long payloads. The robust answer on STM32 is a circular DMA buffer combined with the USART IDLE line interrupt. Here is how it works at register level on STM32F4, how the HAL wraps it, and the details that silently drop bytes when you get them wrong.
The classic first attempt is one interrupt per byte (RXNE) pushing data into a ring buffer. That works at 115200 baud, but at 921600 baud or 2 Mbaud the CPU spends a large share of its time entering and leaving the ISR, and a single higher-priority interrupt that runs a little too long causes an overrun. The second attempt — "DMA for N bytes, then process" — fails as soon as a frame is shorter than N: the DMA simply waits, and your data sits in the buffer until the next frame pushes it out.
The combination that works is: DMA writes every received byte into a circular buffer without CPU involvement, and the CPU is notified when the line goes idle, plus at the half-transfer and transfer-complete points of the buffer. At each notification you read how far the DMA has written and process everything between the last position and the new one.
How IDLE line detection works
The USART sets the IDLE flag when the RX line stays high for one full character time after at least one character has been received. In other words: the sender has stopped, at least for now. With IDLEIE set, this raises the USART interrupt. It does not fire repeatedly while the line stays idle — it needs new data before it can trigger again.
On STM32F4 (and F1, F2) the flag lives in USART_SR and is cleared by a software sequence: read USART_SR, then read USART_DR. On newer families with the reworked USART (F0, F3, F7, L4, G4, H7, U5) it lives in USART_ISR and is cleared by writing IDLECF to USART_ICR. Mixing the two up is a common porting bug: on an H7 the F4-style "read SR then DR" does nothing to the flag, and the interrupt fires forever.
On F4, the clear sequence reads USART_DR. With DMA enabled on reception the DMA has normally already taken the byte, so the read returns stale data and is harmless — but do not use the value. If you ever see a byte "missing" in exactly the position where an IDLE event occurred, check that nothing else in the ISR consumes DR as data.
Register-level setup on STM32F4
Example: USART2 on an STM32F401/F411 at 921600 baud, RX on DMA1 Stream 5 Channel 4 (see the DMA1 request mapping table in RM0368). The DMA stream runs in circular mode, peripheral-to-memory, memory increment enabled, with half-transfer and transfer-complete interrupts.
#define RX_BUF_SIZE 256u
static uint8_t rx_buf[RX_BUF_SIZE];
static volatile size_t rx_old_pos;
void uart2_rx_dma_init(void)
{
RCC->AHB1ENR |= RCC_AHB1ENR_DMA1EN;
RCC->APB1ENR |= RCC_APB1ENR_USART2EN;
/* GPIO (PA3 = USART2_RX, AF7) and baud rate configuration omitted */
DMA1_Stream5->CR &= ~DMA_SxCR_EN; /* stream must be disabled */
while (DMA1_Stream5->CR & DMA_SxCR_EN) { } /* ...and confirmed disabled */
DMA1->HIFCR = DMA_HIFCR_CTCIF5 | DMA_HIFCR_CHTIF5 | DMA_HIFCR_CTEIF5
| DMA_HIFCR_CDMEIF5 | DMA_HIFCR_CFEIF5;
DMA1_Stream5->PAR = (uint32_t)&USART2->DR;
DMA1_Stream5->M0AR = (uint32_t)rx_buf;
DMA1_Stream5->NDTR = RX_BUF_SIZE;
DMA1_Stream5->CR = (4u << DMA_SxCR_CHSEL_Pos) /* channel 4 = USART2_RX */
| DMA_SxCR_MINC /* memory increment */
| DMA_SxCR_CIRC /* circular mode */
| DMA_SxCR_HTIE | DMA_SxCR_TCIE /* half / full events */
| DMA_SxCR_PL_1; /* high priority */
/* DIR = 00: peripheral-to-memory, 8-bit sizes */
DMA1_Stream5->CR |= DMA_SxCR_EN;
USART2->CR3 |= USART_CR3_DMAR; /* RX requests go to DMA */
USART2->CR1 |= USART_CR1_IDLEIE | USART_CR1_RE | USART_CR1_UE;
NVIC_SetPriority(DMA1_Stream5_IRQn, 5);
NVIC_SetPriority(USART2_IRQn, 5); /* same priority: no preemption */
NVIC_EnableIRQ(DMA1_Stream5_IRQn);
NVIC_EnableIRQ(USART2_IRQn);
}
Giving the DMA and USART interrupts the same preemption priority is deliberate: both call the same processing function, and equal priority guarantees they never interrupt each other in the middle of updating rx_old_pos. If you use different priorities, you need a critical section instead.
The processing function: one place, three triggers
The DMA counts NDTR down from the buffer size, and in circular mode reloads it automatically. The current write position is therefore RX_BUF_SIZE - NDTR. Every event — IDLE, half-transfer, transfer-complete — calls the same function, which processes the bytes between the last known position and the current one:
static void rx_check(void)
{
size_t pos = RX_BUF_SIZE - DMA1_Stream5->NDTR;
if (pos == RX_BUF_SIZE) {
pos = 0; /* NDTR reloaded: position wraps to 0 */
}
if (pos != rx_old_pos) {
if (pos > rx_old_pos) {
app_rx(&rx_buf[rx_old_pos], pos - rx_old_pos); /* linear */
} else {
app_rx(&rx_buf[rx_old_pos], RX_BUF_SIZE - rx_old_pos); /* tail */
if (pos > 0) {
app_rx(&rx_buf[0], pos); /* head */
}
}
rx_old_pos = pos;
}
}
void DMA1_Stream5_IRQHandler(void)
{
uint32_t hisr = DMA1->HISR;
if (hisr & DMA_HISR_HTIF5) { DMA1->HIFCR = DMA_HIFCR_CHTIF5; rx_check(); }
if (hisr & DMA_HISR_TCIF5) { DMA1->HIFCR = DMA_HIFCR_CTCIF5; rx_check(); }
if (hisr & DMA_HISR_TEIF5) { DMA1->HIFCR = DMA_HIFCR_CTEIF5; /* log + restart */ }
}
void USART2_IRQHandler(void)
{
if ((USART2->CR1 & USART_CR1_IDLEIE) && (USART2->SR & USART_SR_IDLE)) {
(void)USART2->DR; /* SR read above + DR read clears IDLE (F4) */
rx_check();
}
}
app_rx() receives the data in at most two contiguous chunks. It should copy the bytes into a protocol parser or a queue and return quickly — it runs in interrupt context. Do not parse a complete Modbus frame or run a JSON decoder inside it.
Why half-transfer and transfer-complete matter
IDLE alone is not enough. Suppose the buffer is 256 bytes and a sender streams 1000 bytes without a pause: no IDLE event occurs until the end, and by then the DMA has wrapped around almost four times, overwriting data you never read. The HT and TC interrupts guarantee you are notified at least every half buffer, so you only lose data if your processing cannot keep up with half a buffer's worth of characters.
That gives a simple sizing rule: half the buffer must hold more bytes than can arrive during your worst-case interrupt latency plus processing time. At 921600 baud (8N1) a byte arrives roughly every 10.9 µs, so 128 bytes give you about 1.4 ms. If a flash erase or another long ISR can block you for longer than that, increase the buffer or reconsider priorities.
The same thing with the HAL
Recent STM32Cube HAL versions provide this pattern directly through HAL_UARTEx_ReceiveToIdle_DMA(). Configure the RX DMA channel in circular mode in CubeMX, then:
HAL_UARTEx_ReceiveToIdle_DMA(&huart2, rx_buf, RX_BUF_SIZE);
void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
if (huart->Instance == USART2) {
/* In circular mode, Size is the current write position in rx_buf
(0..RX_BUF_SIZE), not the length of the new data. */
rx_process_up_to(Size);
}
}
Two details catch almost everyone. First, in circular mode Size is the position in the buffer, not the number of new bytes — you still need the old-position logic from rx_check(). Second, the callback fires for half-transfer, transfer-complete and IDLE alike. If you need to know which, call HAL_UARTEx_GetRxEventType() where your HAL version provides it. In normal (non-circular) mode the HAL also re-arms nothing for you: you must call ReceiveToIdle_DMA again from the callback.
Pitfalls that drop bytes in production
| Symptom | Cause | Fix |
|---|---|---|
| Last bytes of a frame appear only when the next frame arrives | IDLE interrupt not enabled or not cleared, only TC used | Enable IDLEIE; clear with the correct sequence for the family |
| Endless USART interrupts on H7/G4/L4 | F4-style clear (read SR, read DR) used on the new USART | Write USART_ICR_IDLECF |
| Garbage or old data on STM32H7/F7 | D-cache holds stale lines of the DMA buffer | Invalidate the buffer range before reading, or place it in a non-cacheable MPU region |
| Occasional corrupted chunk under load | DMA and USART ISRs at different priorities both touching rx_old_pos | Same priority, or protect the update |
| Reception stops after a noise burst | Overrun or framing error left unhandled | Handle ORE/FE/NE, clear them, and check that DMA is still enabled |
| Data lost during long frames | Half-buffer smaller than worst-case latency × byte rate | Resize the buffer using the rule above |
The D-cache case deserves emphasis: on Cortex-M7 parts the DMA writes to SRAM while the CPU may read a cached copy. I covered the mechanics in detail in STM32H7 D-Cache Coherency; for a UART RX buffer the simplest robust choice is a small non-cacheable region.
Practical checklist
- DMA stream in circular mode, peripheral-to-memory, memory increment, HT + TC interrupts enabled.
- Correct DMA stream/channel for your USART, taken from the reference manual's request mapping table.
USART_CR3.DMARset,IDLEIEset, and the IDLE clear sequence matching your family.- One processing function called from IDLE, HT and TC, computing the position from
NDTR. - Wrap-around handled by splitting into at most two chunks.
- Buffer sized from baud rate and worst-case latency, not by habit.
- Error flags (ORE, FE, NE) handled; reception restarts automatically after an error.
- On Cortex-M7: cache maintenance or a non-cacheable buffer.
How I would approach this on a client project
I write this once as a small driver with a byte-stream interface — uart_rx_read(port, buf, max) backed by a lock-free ring buffer — and keep every protocol parser out of interrupt context. Then I test it the way it fails in the field: a USB-UART adapter streaming random-length frames at the highest baud rate the product supports, while a test task deliberately blocks interrupts for increasing periods. The point where bytes start disappearing tells you your real margin, which is far more useful than a calculation on a whiteboard. Finally I add counters for overrun, framing errors and dropped bytes, and expose them over the debug console: when a device misbehaves at a customer site, those counters are the first thing you want to see.
Sources
- ST RM0368 — STM32F401xB/C and STM32F401xD/E Reference Manual: USART chapter (IDLE flag and clearing sequence) and DMA controller chapter (circular mode, NDTR, request mapping).
- ST RM0090 — STM32F405/415, STM32F407/417, STM32F427/437 and STM32F429/439 Reference Manual: same USART and DMA chapters for the larger F4 devices.
- ST UM1725 — Description of STM32F4 HAL and low-layer drivers: UART extended functions (
HAL_UARTEx_ReceiveToIdle_DMA,HAL_UARTEx_RxEventCallback). - ST AN3109 — Communication peripheral FIFO emulation with DMA and DMA timeout in STM32F10x microcontrollers.
- Tilen Majerle — stm32-usart-uart-dma-rx-tx: a widely used reference implementation of this pattern across STM32 families.
Reply to this article by email — I read and respond to every message.