Skip to content
systemcoding.dev
Embedded

Abort a running STM32 DMA transfer with HAL_DMA_Abort

HAL_DMA_Abort stops an STM32 DMA stream in a blocking call that polls for 5 ms, returns HAL_OK, and does not run the abort callback.

1 min read
Summarize in AI

When a transfer has to be cancelled, for example on a protocol timeout, HAL_DMA_Abort is the blocking way to do it in the STM32CubeF4 HAL. It clears the stream enable bit, waits for the hardware to confirm that the stream is off, and sets the handle back to ready, so you can start a new transfer straight away.

abort.cc
void cancel_transfer(DMA_HandleTypeDef *hdma)
{
    HAL_StatusTypeDef rc = HAL_DMA_Abort(hdma);
    printf("%d %d\r\n", (int)rc, hdma->State == HAL_DMA_STATE_READY);
}
Text
0 1

The first number is HAL_OK (0) and the second says the handle returned to the ready state. The function waits at most HAL_TIMEOUT_DMA_ABORT, which is 5 ms, for the EN bit to read zero. If the stream is stuck, you get HAL_ERROR and ErrorCode holds HAL_DMA_ERROR_TIMEOUT, so check the return. Despite the name of the interrupt flavour, HAL_DMA_Abort does not call the XferAbortCallback: only HAL_DMA_Abort_IT does. See the HAL and LL driver manual UM1725.

Do not call HAL_DMA_Abort for a stream that a peripheral driver owns, such as a UART's RX stream. Use HAL_UART_Abort, which also resets the peripheral state, or the UART handle will believe a transfer is still running.

Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.