目录
1.在Keil5中点击上侧的魔法棒,勾选 Use MicroLIB 使用微库。
3.在程序中即可通过指定的串口使用printf函数进行串口数据发送!
一、USART串口重定向:
1.阻塞式发送
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函数进行串口数据发送!
2.DMA发送
usart.c
volatile uint8_t usart_dma_tx_over = 1;
int myprintf(const char *format,...)
{
va_list arg;
static char SendBuff[200] = {0};
int rv;
while(!usart_dma_tx_over);//等待前一次DMA发送完成
va_start(arg,format);
rv = vsnprintf((char*)SendBuff,sizeof(SendBuff)+1,(char*)format,arg);
va_end(arg);
HAL_UART_Transmit_DMA(&huart2,(uint8_t *)SendBuff,rv);
usart_dma_tx_over = 0;//清0全局标志,发送完成后重新置1
return rv;
}
void HAL_UART_TxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance==USART2)
{
usart_dma_tx_over = 1;
}
}
usart.h
#include "stdio.h"
#include "stdarg.h"
#define printf myprintf
int myprintf(const char *format,...);
二、USB虚拟串口重定向:
Win10系统下不需要装任何驱动就能使用USB虚拟串口,但更低版本的系统如:Win7、Win8须要安装ST官方提供的VCP驱动:
https://www.st.com/en/development-tools/stsw-stm32102.html
1.CubeMX配置:
2.程序:
#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");
可加入此句实现回环发送: