STM32單片機(jī)中UART的使用過(guò)程
1、使用UART前必須啟動(dòng)相應(yīng)的外設(shè)時(shí)鐘,其主要用到固件庫(kù)的RCC_APBnPeriphClockCmd函數(shù)。
使能UART1:使用RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE)
使能UART2:使用RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2 , ENABLE)
2、使用中斷進(jìn)行UART操作的需要配置NVIC,設(shè)置中斷優(yōu)先級(jí)。如:
/* Configure the NVIC Preemption Priority Bits */
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_0);
/* Enable the USART1 Interrupt */
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQChannel;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(NVIC_InitStructure);
3、配置相應(yīng)的GPIO口。
如果系統(tǒng)的UART需要進(jìn)行重映射,需要使用GPIO_PinRemapConfig函數(shù)進(jìn)行重映射,如:GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;//注意:Rx為浮空,Tx為第二功能上拉。
將Rx配置為:浮空輸入模式,Tx配置為帶上拉的第二功模式。并用GPIO_Init() 函數(shù)初始化。如:
/* Configure USART2 Rx PA3 input floating */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_3;
GPIO_Init(GPIOA, GPIO_InitStructure);
/* Configure USART1 Tx (PA.09) as alternate push-pull */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA, GPIO_InitStructure);
4、配置UART
當(dāng)在conf文件種配置正確的外晶振后,在USART_InitTypeDef定義的結(jié)構(gòu)體種直接寫(xiě)入U(xiǎn)ART的波特率、通訊長(zhǎng)頓、模式、硬件通訊控制,收發(fā)模式。再用USART_Init()進(jìn)行初始化。如:
USART_InitStructure.USART_BaudRate = 9600;
USART_InitStructure.USART_WordLength = USART_WordLength_8b;
USART_InitStructure.USART_StopBits = USART_StopBits_1;
USART_InitStructure.USART_Parity = USART_Parity_No;
USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
/* Configure USART1 */
USART_Init(USART1, USART_InitStructure);
評(píng)論