// 全局变量 u16 distance = 0; // 串口使用的变量 static u8 Usart1buf[USART1_BUF_SIZE]; static u8 pointer = 0; // 串口1初始化函数 void USART1_Init(void) { USART_InitTypeDef USART1_InitStructure; GPIO_InitTypeDef GPIO_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; // A口时钟 RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE); // A9 -> TX , A10 -> RX GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10; GPIO_InitStructure.GPIO_Speed = GPIO_High_Speed; GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL; GPIO_Init(GPIOA,&GPIO_InitStructure); // 复用功能配置 GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1); GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1); // USART1时钟 RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); // USART1中断优先级 NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 0; NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0; NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; NVIC_Init(&NVIC_InitStructure); // USART1初始化 USART_DeInit(USART1); USART1_InitStructure.USART_BaudRate = 115200; USART1_InitStructure.USART_WordLength = USART_WordLength_8b; USART1_InitStructure.USART_StopBits = USART_StopBits_1; USART1_InitStructure.USART_Parity = USART_Parity_No; USART1_InitStructure.USART_Mode = USART_Mode_Rx|USART_Mode_Tx; USART1_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; USART_Init(USART1,&USART1_InitStructure); USART_Cmd(USART1,ENABLE); USART_ITConfig(USART1,USART_IT_RXNE,ENABLE); } // 串口中断函数 void USART1_IRQHandler(void) { if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET || (USART_GetITStatus(USART1, USART_IT_ORE_RX) != RESET)) { USART_ClearITPendingBit(USART1, USART_IT_RXNE); Usart1buf[pointer++%USART1_BUF_SIZE] = USART_ReceiveData(USART1); // 在此写代码接收程序 if((pointer%USART1_BUF_SIZE >= 9)) { // 包头包尾确认 // 最好加上校验和的验证,此处为了简单,省略了校验和 if( (Usart1buf[pointer%USART1_BUF_SIZE-3]==0x59) &&(Usart1buf[pointer%USART1_BUF_SIZE-4]==0x59)) { //距离 distance=((u16)((Usart1buf[pointer%USART1_BUF_SIZE-1])<<8) |(u16)(Usart1buf[pointer%USART1_BUF_SIZE-2])); } } } } |