重定向发送头文件定义:
#include "stdio.h"
#include "string.h"
#include <stdarg.h>
代码:(放在usart.c)
void Uart_printf(UART_HandleTypeDef *huart,char *format, ...)
{
char buf[512]; //定义临时数组,根据实际发送大小微调
va_list args;
va_start(args, format);
uint16_t len = vsnprintf((char *)buf, sizeof(buf), (char *)format, args);
va_end(args);
HAL_UART_Transmit(huart,(uint8_t *)buf,len,1000);
}
记得在(放在usart.h)声明下函数
/* USER CODE BEGIN Prototypes */
void Uart_printf(UART_HandleTypeDef *huart,char *format, ...);
/* USER CODE END Prototypes */
使用例程:Uart_printf(&huart2,"data = %d",13);
串口接收字符且进行判断
定义接收缓存变量
uint8_t Uart2_Data; //串口2接收缓存量
/* 回调函数 */
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART2)
{
if(Uart2_Data=='A')
{
//当接收到'A's时要做的放这
}
HAL_UART_Receive_IT(&huart2,&Uart2_Data,1);
}
}
}
使用时要在主函数初始化下串口接收:
//开启串口2接收
HAL_UART_Receive_IT(&huart2,&Uart2_Data,1);
串口接收字符串且进行判断
const char String1[8] = "kaishi";
const char String2[11] = "chushihua";
const char String3[9] = "xianshi";
#define RXBUFFERSIZE 256 //最大接收字节数
char RxBuffer[RXBUFFERSIZE]; //接收数据
uint8_t aRxBuffer; //接收中断缓冲
uint8_t Uart1_Rx_Cnt = 0; //接收缓冲计数
串口接收中断回调函数:
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart->Instance == USART1)
{
RxBuffer[Uart1_Rx_Cnt++] = aRxBuffer; //接收数据转存
if((RxBuffer[Uart1_Rx_Cnt-1] == 0x0A)&&(RxBuffer[Uart1_Rx_Cnt-2] == 0x0D)) //判断结束位
{
Uart1_Rx_Cnt = 0;
if(strstr((const char *)RxBuffer,String1) != NULL)
{
//当接收到数据和String1一样时,需要实现的写在这
}
memset(RxBuffer,0x00,sizeof(RxBuffer)); //清空数组
}
HAL_UART_Receive_IT(&huart1, (uint8_t *)&aRxBuffer, 1); //再开启接收中断
}
}