如何使用printf函数将字符串打印到串口

使用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文件开头部分即可。

  • 0
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值