Use Circular DMA With Half-Transfer Interrupts for Streaming
Stream continuous data on an STM32 with circular DMA, process each half buffer on the half-transfer and complete events, and detect a missed deadline.

A normal-mode DMA transfer ends when its count reaches zero, which is exactly wrong for a stream. An ADC samples forever, a UART receives whenever the other side talks, and an I2S microphone never stops. Restarting a transfer after each buffer leaves a gap, a few cycles during which samples have nowhere to go. Circular mode closes the gap: when the count reaches zero the controller reloads it and the addresses and carries on, so the buffer fills again from the start without any software involvement. This post builds the standard streaming pattern on an STM32F407 with STM32CubeF4 firmware V1.28: a circular buffer, half-transfer and complete events to hand out the two halves, and a counter that tells you when the processing fell behind. A second pattern, reading the write position straight from the controller, handles streams of unknown length.
The controller's behavior is in the DMA chapter of the STM32F4 reference manual RM0090. The DMA guide covers the controller's parts if any term here is unfamiliar.
How circular mode and the two events work
Think of the buffer as a clock face. The controller writes at a hand that sweeps around, one unit per request, and returns to the start after the last slot. Two events mark the sweep:
Half transfer, when the hand passes the midpoint. The first half is now complete and will not be written again until the hand comes back around.
Transfer complete, when the hand passes the end and wraps. The second half is complete.
Between the events, the controller is writing into one half while the other sits finished. The CPU's job is to consume each finished half before the hand returns to it. That gives the CPU one half-buffer's worth of time per event, and it is the only deadline in the design.
A buffer of N units at a unit rate f gives a half-buffer period of (N / 2) / f. For N = 512 samples at 20 kilosamples per second, that is 12.8 milliseconds per half.
half period = (512 / 2) / 20,000 = 0.0128 s = 12.8 msThe stream setup
This is an ADC stream triggered by a timer, as in the timer-triggered sampling post, with the DMA in circular mode:
#include "stm32f4xx_hal.h"
#define BUF_LEN 512
#define HALF_LEN (BUF_LEN / 2)
extern ADC_HandleTypeDef hadc1;
extern DMA_HandleTypeDef hdma_adc1;
static uint16_t samples[BUF_LEN];
static volatile uint32_t halves_posted; // incremented by the interrupt
static uint32_t halves_consumed; // incremented by the main loop
static volatile uint8_t which_half; // 0 = first half is ready, 1 = second
void stream_start(void) {
// hdma_adc1 was configured with Mode = DMA_CIRCULAR, half-word widths
HAL_ADC_Start_DMA(&hadc1, (uint32_t *)samples, BUF_LEN);
}
void HAL_ADC_ConvHalfCpltCallback(ADC_HandleTypeDef *hadc) {
(void)hadc;
which_half = 0;
halves_posted++;
}
void HAL_ADC_ConvCpltCallback(ADC_HandleTypeDef *hadc) {
(void)hadc;
which_half = 1;
halves_posted++;
}The callbacks do the smallest possible job: they note which half is ready and count. The main loop picks it up.
extern void process_block(const uint16_t *data, uint32_t len);
void stream_poll(void) {
uint32_t pending = halves_posted - halves_consumed;
if (pending == 0) {
return; // nothing new
}
if (pending > 1) {
stream_overrun(); // one or more halves were lost
}
const uint16_t *block = which_half ? &samples[HALF_LEN] : &samples[0];
process_block(block, HALF_LEN);
halves_consumed = halves_posted;
}pending is the safety net. In normal operation it is 1 whenever it is nonzero. If the main loop was busy for more than one half period, two events passed with no consumption, pending reads 2, and one half of data was overwritten before you looked at it. The code then calls an overrun handler instead of silently processing garbage. Counting with a posted and consumed pair avoids the race that a single flag has: a flag set twice before being cleared looks the same as one event.
What an overrun looks like and what to do
Suppose processing normally takes 4 milliseconds, well inside the 12.8 ms budget, and then a long flash write blocks the main loop for 30 milliseconds. During that time the controller completes two and a half half-buffers. When the loop returns, pending is 2 or 3, and the oldest unread half has been overwritten. The remedies depend on what the data is for.
| Application | Recovery after an overrun |
|---|---|
| Continuous measurement logging | Mark a gap in the log and resume with the latest half |
| Audio output | Mute briefly, or repeat the previous block, to avoid a harsh glitch |
| Control loop | Treat as a fault; control on stale data is worse than a known failure |
| Protocol receive | Discard the frame and resynchronize on the next start marker |
The key point is that the stream continues regardless. Circular DMA never stops for a slow consumer, so the failure is data loss, not a hang, which is why the counter matters. Without it you would see a stretch of corrupted data that looks like noise.
If overruns happen under normal load, the fix is a larger buffer, which gives more time per half, or less work per half. Doubling BUF_LEN doubles the deadline and the RAM.
Reading the write position instead
The two events assume a fixed block size. Many streams do not have one: a UART receives bytes in bursts of unknown length, and a parser wants whatever has arrived whenever it asks. For those, read where the controller currently is. The stream's remaining-count register, NDTR, counts down from the buffer length as units arrive, so the write position, the head, is the buffer length minus the remaining count.
#define RX_LEN 128
extern UART_HandleTypeDef huart2;
extern DMA_HandleTypeDef hdma_usart2_rx;
static uint8_t rx_ring[RX_LEN];
static uint32_t tail; // next byte to consume
void rx_start(void) {
HAL_UART_Receive_DMA(&huart2, rx_ring, RX_LEN); // DMA in circular mode
}
static inline uint32_t rx_head(void) {
return RX_LEN - __HAL_DMA_GET_COUNTER(&hdma_usart2_rx);
}
int rx_read_byte(uint8_t *out) {
if (tail == rx_head()) {
return 0; // nothing new
}
*out = rx_ring[tail];
tail = (tail + 1) % RX_LEN;
return 1;
}Walk through it with an 8-byte ring for clarity. At start, NDTR is 8, so the head is 0, and the tail is 0: empty. After three bytes arrive, NDTR is 5, the head is 3, and the consumer reads positions 0, 1 and 2 and ends with the tail at 3. After eight more bytes, the head has wrapped around and reads 3 again, because NDTR reloaded to 8 when the count reached zero and has counted down to 5. The state is the same as before, with the tail at 3, and the consumer would conclude the buffer is empty when in fact a full lap of data arrived, so the consumer must keep up faster than one lap or it loses the ability to tell full from empty.
head = LEN - NDTR
after 0 bytes: NDTR=8 head=0 tail=0 empty
after 3 bytes: NDTR=5 head=3 tail=0 3 bytes pending
after 11 bytes: NDTR=5 head=3 tail=3 ambiguous: empty, or one full lap behindThe ambiguity is inherent to a ring without a separate fill count, and the rule that resolves it is a deadline, the same as for the half buffer: the consumer must run at least once per lap. For a UART at 115,200 baud, a 128-byte ring takes 128 / 11,520, about 11 milliseconds, to fill. Poll faster than that, from a timer or the main loop, and watch the half-transfer and complete events as a backstop that proves the loop kept pace.
void HAL_UART_RxHalfCpltCallback(UART_HandleTypeDef *huart) { (void)huart; rx_lap_marks++; }
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) { (void)huart; rx_lap_marks++; }If the consumer runs at least once between every two such marks, a half lap, it cannot be lapped.
Pitfalls
Processing a half while the controller is writing it is the original mistake. The which_half logic exists to prevent it. A related bug is processing in the callback itself: it runs in interrupt context, and a long computation there delays everything else, including the next event.
Starting the consumer before the first half completes gives it uninitialized data. Gate on the first event, or zero the buffer first and discard the first block.
Forgetting volatile on the posted counter makes the compiler cache it in a register inside stream_poll, and the loop never sees an update. And on parts with a data cache, the CPU may read stale lines of a buffer the DMA wrote. The cache post covers invalidation.


