串口接收數據幀,可以做通信協議
- #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;
- }
-
-
- }
- }
- }
- }
復制代碼
|