目录
1.在Keil5中点击上侧的魔法棒,勾选 Use MicroLIB 使用微库。
3.在程序中即可通过指定的串口使用printf函数进行串口数据发送!
一、USART串口重定向:
1.在Keil5中点击上侧的魔法棒,勾选 Use MicroLIB 使用微库。
不打开编译会报错的!!!
2.在代码中添加 如下代码
#include "stdio.h"
int fputc(int ch, FILE *f)//printf
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1,0xffff); //发送一个字节的数据到你希望的串口
return (ch);
}
int fgetc(FILE * f)
{
uint8_t ch = 0;
HAL_UART_Receive(&huart1,&ch, 1, 0xffff);
return ch;
}
更改代码中的&huart后的数字即可更改所需要输出的串口!例如&huart1、&huart2、&huart3……
3.在程序中即可通过指定的串口使用printf函数进行串口数据发送!
二、USB虚拟串口重定向:
Win10系统下不需要装任何驱动就能使用USB虚拟串口,但更低版本的系统如:Win7、Win8须要安装ST官方提供的VCP驱动:
https://www.st.com/en/development-tools/stsw-stm32102.html
CubeMX配置:
程序:
#include "stdarg.h"
void usb_printf(const char *format, ...) // usb_printf()重定向
{
va_list args;
uint32_t length;
va_start(args, format);
length = vsnprintf((char *)UserTxBufferFS, APP_TX_DATA_SIZE, (char *)format, args);
va_end(args);
CDC_Transmit_FS(UserTxBufferFS, length);
}
使用时:
CDC_Transmit_FS("hello\r\n",sizeof("hello\r\n"));
//或
usb_printf("hello\r\n");
可加入此句实现回环发送: