使用printf函数将字符串打印到串口(重新定向printf函数)
该函数名已经在标准输入输出库头文 件 <stdio.h> 中定义,原型为 int fputc(int ch, FILE *f)。
在usart.c中添加以下代码:
#ifdef __GNUC__
#define PUTCHAR_PROTOTYPE int __io_putchar(int ch)
#else
#define PUTCHAR_PROTOTYPE int fputchar(int ch, FILE *f)
#endif
PUTCHAR_PROTOTYPE
{
//串口号自己根据需要改
HAL_UART_Transmit(&Uarthandle, (uint8_t*)&ch,1,HAL_MAX_DELAY);
//Uarthandle为串口号,例如huart1
return ch;
}
最后不要忘了在usart.h文件中加入#include <stdio.h>
添加以上代码之后,可以进行试验。
int main(void)
{
uint8_t tx_buf[] = "Usart Test!\r\n";
SystemClock_Config();
HAL_Init();
MX_GPIO_Init();
MX_USART1_UART_Init();
printf("Usart is OK!\r\n");
while(1)
{
HAL_UART_Transmit(&huart1, "hello world!\r\n", 16 , 20);
HAL_Delay(500);
HAL_UART_Transmit(&huart1, tx_buf, 16 , 20);
HAL_Delay(500);
}
}
printf函数还有另一种简单的写法(HAL库为例):
#include <stdio.h>
int fpuc(int ch, FILE *f)
{
HAL_UART_Transmit(&huartx, (uint8_t*) &ch, 1, 10);
return ch;
}
可直接将此代码放在main.c文件开头部分即可。