STM32L412KB UART Data Corruption After Random Periods
Hello, I’m working with an STM32L412KB on an evaluation board, and I’m facing an issue with receiving UART data. Here’s a quick overview:
- Setup: The device receives 5-byte packets over UART every 30 ms using the HAL UART interrupt mode (HAL_UART_Receive_IT).
- Issue: After running for a few minutes, the received packet occasionally gets corrupted—typically with the first and last byte becoming swapped or confused.
- Attempted Fixes: I’ve cleared error flags in the HAL_UART_ErrorCallback, and I’m restarting UART with DMA after an error, but the corruption persists.
- I have tried DMA and circular buffer, but the results are the same
- Below is a code example showing the logic (I cannot share the actual code due to NDA constraints):.
HAL_UART_Receive_IT(&UART, packet, BUFF_SIZE); // Initiate UART receive in interrupt mode
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart) {
flag = 1; // Signal main loop to process packet
HAL_UART_Receive_IT(&huart1, packet, BUFF_SIZE); // Re-initiate UART receive
}
void HAL_UART_ErrorCallback(UART_HandleTypeDef *huart) {
__HAL_UART_CLEAR_PEFLAG(huart); // Clear UART error flags
HAL_UART_Receive_IT(huart, packet, BUFF_SIZE); // Restart UART in DMA mode
}
void system_main(void) {
for (;;) {
if (flag) {
// Process each byte in the packet
process_value(packet[0], DEFAULT_PACKET);
process_value(packet[1], DEFAULT_PACKET);
process_value(packet[2], DEFAULT_PACKET);
process_value(packet[3], DEFAULT_PACKET);
process_value(packet[4], BUTTON_PACKET);
// Clear the buffer and reset the flag
memset(packet, 0, sizeof(packet));
flag = 0;
}
// here some work with hal_gpio API and dealys
}
}
