21.10.15
0,重映射
#include <stdio.h>
void lb_uart_sendbyte(uint8_t *str)
{
HAL_UART_Transmit(&huart1,str,1,1000);
}
void lb_uart_sendstring(uint8_t *str)
{
unsigned int k=0;
do
{
HAL_UART_Transmit(&huart1,(uint8_t *)(str + k) ,1,1000);
k++;
} while(*(str + k)!='\0');
}
int fputc(int ch, FILE *f)
{
HAL_UART_Transmit(&huart1, (uint8_t *)&ch, 1, 1000);
return (ch);
}
int fgetc(FILE *f)
{
int ch;
HAL_UART_Receive(&huart1, (uint8_t *)&ch, 1, 1000);
return (ch);
}
1,使用串口接收中断方式,接收固定长度字符,以指定字符开头,且以指定字符结尾
如:FD 31 54 0C 01 DF FD 31 54 0C 01 DF
0,cubemx中配置串口为ASYNC,且开启串口中断
1,mian.c中定义全局变量
#define uart1_rev_size 6
uint8_t uart1_rev_buf[6]={0x00};
uint8_t uart1_rev_onebyte [1]={0};
2,main.c中main函数的while前调用接收中断
HAL_UART_Receive_IT(&huart1,uart1_rev_onebyte,1);
3,while中执行用户逻辑
4,main.c的最后放接收中断完成回调函数
void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
if(huart==&huart1)
{
static uint8_t USART1_Receive_buff[uart1_rev_size]={0x00};
static uint8_t Uart1_Receive_Number=0;//一次性接收了多少个数据
static uint8_t Uart1_Receive_enable=0;//是否使能接收数据
if(uart1_rev_onebyte[0]==0xFD )//如果收到了帧头:
{
Uart1_Receive_enable=1; //使能接收
Uart1_Receive_Number=0;//从第零位开始接收。
memset(USART1_Receive_buff, 0, sizeof(USART1_Receive_buff));//清空接收区数据
}
else if(uart1_rev_onebyte[0]==0xDF && Uart1_Receive_Number==uart1_rev_size-1)//如果收到了帧尾,并且数据长度正常。
{
USART1_Receive_buff[Uart1_Receive_Number]=uart1_rev_onebyte[0];//将帧尾放进去后,再使能接收
Uart1_Receive_enable=0;//失能接收
Uart1_Receive_Number=0;//清零接收位。
memcpy(uart1_rev_buf,USART1_Receive_buff,sizeof(USART1_Receive_buff));
HAL_UART_Transmit(&huart1,uart1_rev_buf,uart1_rev_size,0xffff);
}
if(Uart1_Receive_enable==1)//如果接收被使能,开始接收数据
{
USART1_Receive_buff[Uart1_Receive_Number]=uart1_rev_onebyte[0];
Uart1_Receive_Number++;
}
HAL_UART_Receive_IT(&huart1, uart1_rev_onebyte, 1);//开启下一次接收中断
}
}
声明:
本文采用
BY-NC-SA
协议进行授权,如无注明均为原创,转载请注明转自
走着的小站
本文地址: stm32 hal串口的各种使用方式
本文地址: stm32 hal串口的各种使用方式