STM32单片机中UART的使用过程
1、使用UART前必须启动相应的外设时钟,其主要用到固件库的RCC_APBnPeriphClockCmd函数。
使能UART1:使用RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE)
使能UART2:使用RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2 , ENABLE)
2、使用中断进行UART操作的需要配置NVIC,设置中断优先级。如:
/* 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、配置相应的GPIO口。
如果系统的UART需要进行重映射,需要使用GPIO_PinRemapConfig函数进行重映射,如: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() 函数初始化。如:
/* 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
当在conf文件种配置正确的外晶振后,在USART_InitTypeDef定义的结构体种直接写入UART的波特率、通讯长顿、模式、硬件通讯控制,收发模式。再用USART_Init()进行初始化。如:
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);
评论