您的位置 首页 培训

STM32串口中止接纳一个完好的数据帧

代码运行条件:(1)大端发送;(2)上位机发送一帧数据的时间间隔不能大于主循环周期;(3)数据帧满足下面格式:帧头部(Head)类型(Typ…

代码运转条件:

(1)大端发送;
(2)上位机发送一帧数据的时刻距离不能大于主循环周期;

(3)数据帧分量下面格局:

帧头部(Head)

类型(Type)

长度(Length)

值(Value)

CRC校验

2字节

1字节

1字节

X字节

2字节

0xaa 0x55

X

void USART6_Init (void) {GPIO_InitTypeDef	GPIO_InitStructure;USART_InitTypeDef	USART_InitStructure;NVIC_InitTypeDef	NVIC_InitStructure;RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART6,ENABLE);RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOC,ENABLE); //修正GPIO_InitStructure.GPIO_Pin	= GPIO_Pin_6|GPIO_Pin_7;//修正GPIO_InitStructure.GPIO_Mode	= GPIO_Mode_AF;GPIO_InitStructure.GPIO_OType	= GPIO_OType_PP;GPIO_InitStructure.GPIO_PuPd	= GPIO_PuPd_NOPULL;GPIO_InitStructure.GPIO_Speed	= GPIO_Speed_50MHz;GPIO_Init(GPIOC,&GPIO_InitStructure);//修正GPIO_PinAFConfig(GPIOC,GPIO_PinSource6,GPIO_AF_USART6);//修正GPIO_PinAFConfig(GPIOC,GPIO_PinSource7,GPIO_AF_USART6);	//修正NVIC_InitStructure.NVIC_IRQChannel = USART6_IRQn;NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 2;NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_Init(&NVIC_InitStructure);USART_InitStructure.USART_BaudRate = 115200;USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;USART_InitStructure.USART_Mode = USART_Mode_Tx|USART_Mode_Rx;USART_InitStructure.USART_Parity = USART_Parity_No;USART_InitStructure.USART_StopBits = USART_StopBits_1;USART_InitStructure.USART_WordLength = USART_WordLength_8b;USART_Init(USART6,&USART_InitStructure);USART_ITConfig(USART6,USART_IT_RXNE,ENABLE);//翻开接纳中止USART_Cmd(USART6,ENABLE);}void USART6_IRQHandler(){unsigned char rCh;static char rCnt = 0;if(USART_GetITStatus(USART6,USART_IT_RXNE) != RESET){rCh = USART_ReceiveData(USART6);COM6_RecvBuf[rCnt] = rCh;if(rCnt == 0)     //帧头0xAA    {rCnt = (0xAA != rCh)?0:rCnt+1;}else if(rCnt == 1) //帧头0x55  {rCnt = (0x55 != rCh)?0:rCnt+1;}else if(rCnt == 2) //类型type{//这儿能够依据类型的规模进行如上的处理rCnt++;}else if(rCnt == 3) //长度len{rCnt++;}			else if(rCnt > 3) //值value{rCnt++;if(rCnt == 6+COM6_RecvBuf[3]){             rCnt = 0;memcpy(COM6_RecvBufBck,COM6_RecvBuf,RECV_BUF_SZ);//缓冲COM6_RecvFin = 1;  //告诉主循环处理}}}}int  main(void){int i;//代码段1while(1)//该循环不能太慢,不然数据缓冲区会被部分修正{//代码段2if(COM6_RecvFin == 1){COM6_RecvFin = 0;CMD_Analysis();//剖析接纳到的这帧数据}//代码段3}return  0;}//在今后再仔细剖析数据接纳较快而处理较慢的问题吧,本课题首要评论的是怎么完好的接纳一个数据帧,在数据源正确的状况下不丢帧

声明:本文内容来自网络转载或用户投稿,文章版权归原作者和原出处所有。文中观点,不代表本站立场。若有侵权请联系本站删除(kf@86ic.com)https://www.86ic.net/changshang/peixun/264801.html

为您推荐

联系我们

联系我们

在线咨询: QQ交谈

邮箱: kf@86ic.com

关注微信
微信扫一扫关注我们

微信扫一扫关注我们

返回顶部