stm32串口接收數(shù)據(jù)程序
void init_usart(void)
//RCC初始化
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO,,ENABLE);//使能GPIOA時(shí)鐘
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;
//串口設(shè)置恢復(fù)默認(rèn)參數(shù)
USART_ClockInitTypeDef USART_ClocklnitStructure;
USART_InitStructure.USART_BaudRate = 9600;
//波特率9600
USART_InitStructure.USART_WordLength = USART_WordLength_8b;//字長(zhǎng)8位USART_InitStructure.USART_StopBits = USART_StopBits_1;
//1位停止字節(jié)
USART_InitStructure.USART_Parity = USART_Parity_No;
川/無(wú)奇偶校驗(yàn)
USART_IlnitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//無(wú)流控制
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//打開Rx接收和Tx發(fā)送功能
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);//開啟接收中斷,這個(gè)必須在打開串口之前設(shè)置USART_Cmd(USART2,ENABLE);
/啟動(dòng)串口
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;
}
//溢出-如果發(fā)生溢出需要先讀SR,再讀DR寄存器則可清除不斷入中斷的問題[牛人說(shuō)要這樣]if(USART_GetFlagStatus(USART2,USART_FLAG_ORE)==SET)
USART_ClearFlag(USART2,USART_FLAG_ORE);//讀SR其實(shí)就是清除標(biāo)志USART_ReceiveData(USART2);//讀DR
}
}
文章整合自:dgzj
編輯:ymf
-
STM32
+關(guān)注
關(guān)注
2273文章
10928瀏覽量
357895 -
串口接收
+關(guān)注
關(guān)注
0文章
8瀏覽量
9288
發(fā)布評(píng)論請(qǐng)先 登錄
相關(guān)推薦
RS232串口連接方式及注意事項(xiàng)
FT232芯片設(shè)計(jì)的USB轉(zhuǎn)RS232串口原理圖
快速實(shí)現(xiàn)C2000串口程序升級(jí)
![快速實(shí)現(xiàn)C2000<b class='flag-5'>串口</b><b class='flag-5'>程序</b>升級(jí)](https://file.elecfans.com/web1/M00/D9/4E/pIYBAF_1ac2Ac0EEAABDkS1IP1s689.png)
評(píng)論