If your STM32 UART keeps delivering old or unexpected characters, you may need to clear its receive buffer before starting a new message. The right approach depends on what you mean by “buffer”: bytes waiting in the UART peripheral, a software buffer managed by your code, or a DMA buffer. STM32 does not provide one universal command that safely clears all three.
In this guide, you’ll learn how to clear stale UART data with STM32 HAL, reset a software ring buffer, handle interrupt- and DMA-based reception, and avoid common mistakes that can cause lost data or UART errors.
What Does “Clear the UART Buffer” Mean on STM32?
A UART receive path can contain data in several places. Before clearing anything, identify where the unwanted bytes are stored:
- UART hardware: A received byte may be waiting in the peripheral’s receive register or FIFO. The exact register names and FIFO behavior vary between STM32 families.
- HAL receive destination: HAL may be writing incoming bytes into the array you passed to a receive function.
- Application buffer: Your code may copy received bytes into a queue, ring buffer, or message array.
- DMA buffer: DMA may be moving incoming data into memory while the UART is receiving.
Clearing one layer does not automatically clear the others. For example, setting a software buffer’s index to zero does not remove bytes already waiting in the UART peripheral. Likewise, draining the peripheral does not erase data already copied into an application array.
Clear a Software Buffer
If your application stores received characters in a normal array, you can reset the array or reset the variables that track its contents. Resetting the length or read/write indices is often sufficient; clearing every byte is only necessary if the contents must be erased for security or debugging reasons.
memset(rx_buffer, 0, sizeof(rx_buffer));
rx_length = 0;
For a ring buffer, reset both indices using the same synchronization method your receive code uses. If an interrupt can update an index while the main loop resets it, protect the operation briefly. The exact critical-section functions depend on your project and RTOS.
// Example only: adapt the critical section to your application.
__disable_irq();
rx_head = 0;
rx_tail = 0;
__enable_irq();
Disabling interrupts globally can affect other timing-sensitive code, so keep the protected section short. In an RTOS, use an appropriate critical-section or mutex mechanism instead. Also consider whether data can arrive during the reset. If it can, your software may immediately receive new bytes into the “cleared” buffer.
Drain Bytes Waiting in the UART Peripheral
To discard stale hardware-received data, stop any active receive operation first, then read and discard pending bytes using a method supported by your STM32 family and software setup. With HAL, a simple blocking approach is to receive one byte at a time with a short timeout. Use it only when no interrupt- or DMA-based receive operation is currently using the same UART handle.
HAL_UART_AbortReceive(&huart1);
uint8_t discarded;
while (HAL_UART_Receive(&huart1, &discarded, 1, 1) == HAL_OK)
{
// Discard each byte already received.
}
The timeout in this example is in milliseconds. The loop ends when no byte is available within the timeout. Check the return values for your HAL version and application: aborting can fail, and other UART errors may need handling. Do not run this blocking drain routine inside a UART interrupt callback or another time-critical context.
Some STM32 families and HAL versions offer different receive or flag-clearing behavior. At the register level, the peripheral may use a receive data register, a FIFO, or family-specific status flags. Consult the reference manual for your exact MCU before reading or clearing registers directly. Avoid writing arbitrary values to status registers: many UART flags have specific clearing sequences, and the required sequence differs by peripheral generation.
Clear a UART Buffer in Interrupt-Based Reception
With interrupt-based reception, HAL usually writes received bytes to the memory address supplied when you start the receive operation. A common pattern receives one byte at a time and processes it in HAL_UART_RxCpltCallback. In that setup, there may not be a separate HAL queue to clear; your code is responsible for managing the bytes it has collected.
To discard a partial message, reset your application’s message length and state. If you also want to discard bytes that arrive while resetting, pause or abort reception, clear the application state, drain any pending peripheral data if appropriate, and then start reception again. Avoid calling a blocking receive function from the callback.
static uint8_t rx_byte;
static char message[64];
static size_t message_length;
void start_uart_receive(void)
{
HAL_UART_Receive_IT(&huart1, &rx_byte, 1);
}
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if (huart->Instance == USART1)
{
// Process or store rx_byte here.
// Re-arm reception for the next byte.
HAL_UART_Receive_IT(huart, &rx_byte, 1);
}
}
void discard_partial_message(void)
{
message_length = 0;
}
This is a simplified pattern, not a complete parser. In production code, check the return value from HAL_UART_Receive_IT, handle errors, and ensure the callback cannot write into the message while the main thread resets it. A better design may set a discard request for the callback to apply safely.
Clear or Restart DMA-Based UART Reception
DMA adds another layer: the peripheral can continue receiving while DMA writes into memory. Do not clear or reuse a DMA buffer while DMA is actively writing to it unless your design explicitly coordinates that access. First stop the receive operation using the appropriate HAL function, then reset your application’s indices or buffer state and start DMA reception again.
// Simplified example. Check return values and adapt to your HAL version.
HAL_UART_AbortReceive(&huart1);
memset(rx_dma_buffer, 0, sizeof(rx_dma_buffer));
rx_read_index = 0;
HAL_UARTEx_ReceiveToIdle_DMA(&huart1,
rx_dma_buffer,
sizeof(rx_dma_buffer));
HAL_UARTEx_ReceiveToIdle_DMA is available in supported STM32 HAL packages, but not every project or HAL version includes it. Some applications use HAL_UART_Receive_DMA instead. Follow the API provided by your installed STM32Cube package, and check the function’s return value before assuming reception restarted.
For circular DMA, resetting an application read index does not reset the DMA write position. Your code must account for the DMA counter or position when determining which bytes are new. If you need to discard input, stop or pause DMA in a controlled way, synchronize with the DMA position, and then resume. Otherwise, a reset can make old bytes appear new, or new bytes appear to be overwritten.
Handle UART Errors Before Restarting Reception
Overrun, framing, noise, and parity errors can interrupt reception or leave the HAL handle in an error state. An overrun typically means another character arrived before the previous data was read. In many HAL-based projects, the error callback is where you record the problem and arrange recovery.
Do not assume that clearing a buffer also clears UART error flags or restores the HAL receive state. Use the HAL recovery procedures appropriate to your STM32 family and HAL version. Depending on the situation, recovery may involve aborting reception, handling the error, and starting the receive operation again. Check the HAL return codes and the reference manual if you are working directly with peripheral registers.
Common Mistakes to Avoid
- Resetting only the array: This does not necessarily empty the peripheral, a DMA transfer, or a separate ring buffer.
- Clearing memory while DMA is active: DMA can overwrite your changes immediately or create inconsistent data.
- Mixing receive methods on one handle: Do not start blocking, interrupt, and DMA reception concurrently on the same UART unless your design and HAL usage explicitly support it.
- Calling blocking functions in callbacks: Blocking inside an interrupt callback can stall the system or cause timing problems.
- Assuming all STM32 UARTs behave alike: Register layouts, FIFO support, flags, and HAL APIs differ across STM32 families.
- Ignoring errors and return values: A buffer reset is not useful if the UART remains in an error state or reception never restarts.
A Reliable Buffer-Clearing Sequence
For many applications, a safe sequence is to stop the current receive operation, handle any reported UART error, discard pending hardware bytes when appropriate, reset the application’s buffer state, and then restart reception. Adapt the details to whether you use polling, interrupts, DMA, or a custom ring buffer.
- Determine which layer contains the unwanted bytes.
- Pause, abort, or synchronize the active receive mechanism.
- Clear the relevant software data or reset its indices.
- Drain peripheral data only when no other receive method is using the UART.
- Check for UART errors and inspect all HAL function results.
- Restart reception and confirm that new bytes are being processed.
For robust communication, it is usually better to use message framing—such as a delimiter, fixed-length packet, or length field—than to rely on clearing a buffer between messages. Framing helps your parser distinguish a complete new message from leftover or partial data, especially when bytes can arrive at any time.
Conclusion
To clear an STM32 UART buffer, first identify whether the data is in the hardware peripheral, a software buffer, or a DMA-managed memory area. Reset software indices for application data, and stop or synchronize interrupt and DMA reception before changing buffers they may be using. Drain pending hardware bytes only with a method suitable for your STM32 family and current receive mode. Because UART registers and HAL behavior vary between devices, verify the details in your MCU reference manual and HAL documentation before using low-level flag operations. A clear receive strategy, proper error handling, and reliable message framing will prevent stale UART data from disrupting your STM32 application.
Disclaimer: Articles are written by Humans, AI or Both. Verify Important information.