相信大家在用到STM32的时候都会用到此功能,由于自己画图时候没注意串口的默认管脚,串口都用在了复用的管脚上,查了很多开发版的资料,都是在默认的初始化,所以找了好多资料,不多说直接上代码,下面为USART2初始化
void uart2_init(u32 bound)
{
RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2, ENABLE); //使能USART2
RCC_APB2PeriphClockCmd(RCC_APB2Periph_GPIOD, ENABLE); //GPIOD时钟
RCC_APB2PeriphClockCmd(RCC_APB2Periph_AFIO, ENABLE); //使能AFIO功能的时钟(勿忘!)
GPIO_PinRemapConfig(GPIO_Remap_USART2, ENABLE); //打开重映射
//USART2_TX GPIOD.5
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5; //PD.5
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP; //复用推挽输出
GPIO_Init(GPIOD, &GPIO_InitStructure);//初始化GPIOD.5
//USART2_RX GPIOD.6初始化
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;//PD6
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING; //浮空输入;
GPIO_Init(GPIOD, &GPIO_InitStructure);//初始化GPIOD.6
//USART2 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn;
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3 ;//抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能
NVIC_Init(&NVIC_InitStructure); //根据指定的参数初始化VIC寄存器
//USART 初始化设置
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //设置中断组,4位抢占优先级,4位响应优先级;
huare2.USART_BaudRate = bound;//串口波特率
huare2.USART_WordLength = USART_WordLength_8b;//字长为8位数据格式
huare2.USART_StopBits = USART_StopBits_1;//一个停止位
huare2.USART_Parity = USART_Parity_No;//无奇偶校验位
huare2.USART_HardwareFlowControl = USART_HardwareFlowControl_None;//无硬件数据流控制
huare2.USART_Mode = USART_Mode_Rx | USART_Mode_Tx; //收发模式
USART_Init(USART2, &huare2); //初始化串口2
USART_ITConfig(USART2, USART_IT_RXNE, ENABLE);//开启串口接受中断
USART_Cmd(USART2, ENABLE); //使能串口2
}