To develop with microcontrollers like STM32, the most common way to output debug messages is through UART. I believe it is also the habit of most developers. In this article, I will introduce how to redirect printf to UART on STM32.
In fact, the example can be found in the ST sample package. I searched for an example and found the UART_printf project in the STM32F411RE-Nucleo board.
Just add two lines of code in main.c and add the following code in the Define section of the variable section:
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif /* __GNUC__ */
Then add the following function anywhere, my habit is to put it before SystemClock_Config(void):
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);
return ch;
}
This function overrides the standard putchar function and sends the character to UART using the HAL_UART_Transmit function.
Finally, in the main function, you can use printf to output messages to UART.