stm32串口接收数据程序
void init_usart(void)
//RCC初始化
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,,ENABLE);//使能GPIOA时钟
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);
//nvic
NVIC_ InitTypeDef NVIC_InitStructure;#ifdef VECT_TAB_RAM
NVIC_SetVectorTable(NVIC_VectTab_RAM,Ox0);#else
NVIC_SetVectorTable(NVIC_VectTab_FLASH,Ox0);#endif
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;NVIC_InitStructure.NVIC_IRQChannelSubPriority = o;NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;NVIC_Init(&NVIC_lnitStructure);
//GPIO初始化
GPIO_IlnitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;GPIO_IlnitStructure.GPIO_Speed = GPIO_Speed_5OMHz;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_2;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;GPIO_InitStructure.GPIO_Speed = GPIO_Speed_5OMHz;GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//USART初始
//USART_DeInit(USART2);
USART_InitTypeDef USART_InitStructure;
//串口设置恢复默认参数
USART_ClockInitTypeDef USART_ClocklnitStructure;
USART_InitStructure.USART_BaudRate = 9600;
//波特率9600
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字长8位USART_InitStructure.USART_StopBits = USART_StopBits_1;
//1位停止字节
USART_InitStructure.USART_Parity = USART_Parity_No;
川/无奇偶校验
USART_IlnitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//打开Rx接收和Tx发送功能
USART_ClockInitStructure.USART_Clock =USART_Clock_Disable;USART_ClockInitStructure.USART_CPOL =USART_CPOL_High;USART_ClockInitStructure.USART_CPHA =USART_CPHA_2Edge;USART_ClocklnitStructure.USART_LastBit =USART_LastBit_Disable;USART_Clocklnit(USART2,&USART_ClockInitStructure);
USART_Init(USART2,&USART_InitStructure);
//初始化
USART_ITConfig(USART2,USART_IT_RXNE,ENABLE);//开启接收中断,这个必须在打开串口之前设置USART_Cmd(USART2,ENABLE);
/启动串口
void USART2_IRQHandler(void)
//接收中断
if(USART_GetlTStatus(USART2,USART_IT_RXNE)==SET)(
USART_ClearlTPendingBit(USART2,USART_IT_RXNE);usart_rx=USART_ReceiveData(USART2);
usart_rx_flag=1;
}
//溢出-如果发生溢出需要先读SR,再读DR寄存器则可清除不断入中断的问题[牛人说要这样]if(USART_GetFlagStatus(USART2,USART_FLAG_ORE)==SET)
USART_ClearFlag(USART2,USART_FLAG_ORE);//读SR其实就是清除标志USART_ReceiveData(USART2);//读DR
}
}
文章整合自:dgzj
编辑:ymf
-
STM32
+关注
关注
2270文章
10895浏览量
355728 -
串口接收
+关注
关注
0文章
8浏览量
9246
发布评论请先 登录
相关推荐
评论