标题:
STM32单片机串口接收一帧数据
[打印本页]
作者:
sr861126
时间:
2021-6-24 17:08
标题:
STM32单片机串口接收一帧数据
串口接收数据帧,可以做通信协议
#include "sys.h"
#include "usart.h"
#define len 5 //数组长度
#define a PCout(13)
u8 rx_buff[8];//接收缓存
u8 rx_done =0;//接收完成标志
u8 rx_cnt=0;//接收数据长度
u8 rx3_cont=0;
u8 rx3_done=0;
u8 rx_data[7];//复位与步进接收缓冲区数据
u8 stop_data[7];
u8 num=0; // 字节数
u8 buf[5]; //接收缓冲,最大9个字节.
void MAX485_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOC,ENABLE);
// RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE);
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_13;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_PP;
GPIO_Init(GPIOC, &GPIO_InitStructure);
a=1;
}
void USART1_Config(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStructure;
NVIC_InitTypeDef NVIC_InitStructure;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA, ENABLE);//使能串口GPIO的时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);//使能串口外设的时钟
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_9;//将USART1 Tx的GPIO配置为推挽复用模式
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_AF_PP;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_10;//将USART1 Rx的GPIO配置为浮空输入模式
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
USART_InitStructure.USART_BaudRate=115200;//配置波特率115200
USART_InitStructure.USART_WordLength=USART_WordLength_8b;//配置数据字长8bit
USART_InitStructure.USART_StopBits=USART_StopBits_1;//配置停止位1bit
USART_InitStructure.USART_Parity=USART_Parity_No;//校验位无
USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//硬件流控制无
USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//同时收发模式
USART_Init(USART1,&USART_InitStructure);//完成串口的初始化配置
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_1);//嵌套向量中断控制器组选择
NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;//配置USART为中断源
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=0;//抢断优先级
NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;//子优先级
NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;//使能中断
NVIC_Init(&NVIC_InitStructure);//初始化配置NVIC
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能串口接收中断
//USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);//空闲中断使能
USART_Cmd(USART1,ENABLE);
}
void USART1_IRQHandler(void)
{
u8 res;
if(USART_GetITStatus(USART1,USART_IT_RXNE)!=RESET)//接收到一个字节,进入一次接收中断
{
USART_ClearITPendingBit(USART1,USART_IT_RXNE);//清除接收中断标志
res=USART_ReceiveData(USART1);//将接收的数据存入rx_buff中
if(num>0)
{
buf[num]=res;
num++;
}
else if (res==0xc1) // 包头
{
buf[0]=0xc1;//前面写进,后面才能读
num=1;
}
if(num>=len)
{
num=0;
if(buf[(len-1)]==0x0d) // 判断包尾
{
if(buf[0]==0xc1) a=0;
else
a=1;
if(buf[1]==5)
{
a=1;
}
}
}
}
}
复制代码
欢迎光临 (http://www.51hei.com/bbs/)
Powered by Discuz! X3.1