学过C语言一定非常熟悉printf函数的用法,在STM32编程中可否也使用printf函数直接向uart硬件接口发送数据呢?当然可以,你需要做的只是重映射一下PUTCHAR_PROTOTYPE函数,调用HAL库uart阻塞式发送函数:HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF);,将下面代码里的&huart1换成你实际使用的对应接口即可。
我实测电路的硬件是将嵌入式热敏打印机通过uart1对应接口连接STM32F103C8T6单片机,在附上下面的代码后,即可随意使用printf函数向打印机发送打印内容了。
/**** STM32-printf重映射串口,需#include "stdio.h" 注意,使用printf处也需#include "stdio.h" ****/
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputc(int ch, FILE* f)
#endif /* __GNUC__ */
#ifdef __cplusplus
extern "C" {
#endif //__cplusplus
PUTCHAR_PROTOTYPE
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 0xFFFF); //调用STM32的HAL库发送一个字节,此项目使用&huart1接口,根据实际调整
return (ch);
}
#ifdef __cplusplus
}
#endif //__cplusplus
/***** STM32-printf重映射串口 ****/