STM32串口1(PA9 & PA10)的基本代码配置如下:
void USART1_Configuration(void)//串口1的配置函数
{
GPIO_InitTypedef GPIO_InitStructure;
USART_InitTypedef USART_InitStructure;
NVIC_InitTypedef NVIC_InitStructure;
//使能时钟频率
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | RCC_APB2Periph_GPIOA | RCC_APB2Periph_AFIO , ENABLE);
//端口初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9; //端口9用于发送数据
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10; //端口10用于接收数据
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
GPIO_Init(GPIOA,&GPIO_InitStructure);
//串口配置
USART_InitStructure.USART_BaudRate = 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_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件控制流
USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;//收发模式
USART_Init(USART1,&USART_InitStructure);//配置串口参数
//中断配置
USART_ITConfig(USART1,USART_IT_TXE,ENABLE);//使能发送中断
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能接收中断
USART_ITConfig(USART1,USART_IT_IDLE,ENABLE);//使能空闲中断
USART_Cmd(USART1,ENABLE);//使能USART1外设
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3;
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 2;
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStructure);
}