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
+關注
關注
2290文章
11018瀏覽量
362691 -
串口接收
+關注
關注
0文章
8瀏覽量
9396
發布評論請先 登錄
評論