要在STM32上使用打印输出到串口功能,基本思路是重定义putchar或者fputc函数,实现方法如下(以芯片STM32F4xx系列为例):
#define USE_IAR
#ifdef USE_IAR
#define PUTCHAR_PROTOTYPE int putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 10);
return ch;
}
重定义之后,便可以在main函数中使用printf函数,打印信息会从串口huart1中输出。HAL_UART_Transmit()函数为调用串口底层驱动函数,其定义在drivers\stm32f4xx_hal_driver\src\stm32f4xx_hal_uart.c中,每次打印一个字符,阻塞模式。
另外,需要在IAR工程中打开Options->General Options->Library Configuration,设置Library为Full即可。