
原码镇楼:void HalUart2_Init(void) { GPIO_InitTypeDef GPIO_InitStructure; USART_InitTypeDef USART_InitStructure; NVIC_InitTypeDef NVIC_InitStructure; RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOD,ENABLE); //使能GPIOD时钟 RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE);//使能USART2时钟 //串口2对应得引脚复用映射 GPIO_PinAFConfig(GPIOD,GPIO_PinSource5,GPIO_AF_USART2); //GPIOD5复用为USART2 GPIO_PinAFConfig(GPIOD,GPIO_PinSource6,GPIO_AF_USART2); //GPIOD6复用为USART2 //USART2端口配置 GPIO_InitStructure.GPIO_Pin = GPIO_Pin_5 | GPIO_Pin_6; //GPIOD5与GPIOD6 GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF; //复用功能 GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz; //速度50MHz GPIO_InitStructure.GPIO_OType = GPIO_OType_PP; //推挽复用输出 GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP; //上拉 GPIO_Init(GPIOD,&GPIO_InitStructure); //初始化PD5,PD6 //USART2 端口配置 USART_InitStructure.USART_BaudRate = 9600; //波特率 USART_InitStructure.USART_WordLength = USART_WordLength_8b; //字长为8位数据格式 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; //收发模式 USART_Init(USART2, &USART_InitStructure); //初始化串口1 USART_Cmd(USART2, ENABLE); //使能串口2 //USART_ClearFlag(USART2, USART_FLAG_TC); #ifdef EN_USART2_RX USART_ITConfig(USART2, USART_IT_RXNE, ENABLE); //开启相关中断 //Usart2 NVIC配置 NVIC_InitStructure.NVIC_IRQChannel = USART2_IRQn; //串口2中断通道 NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=3; //抢占优先级3 NVIC_InitStructure.NVIC_IRQChannelSubPriority =3; //子优先级3 NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; //IRQ通道使能 NVIC_Init(&NVIC_InitStructure); #endif } void HalUart2_SendByte(uint8 byte) { USART_ClearFlag(USART2,USART_FLAG_TC); USART_SendData(USART2,byte); while(USART_GetFlagStatus(USART2,USART_FLAG_TC) != SET); } 说明:其中很多人USART2/3无法发送数据, 1、APB1的时钟大于42MHZ 2、将RCC_APB1PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); 写成RCC_APB2PeriphClockCmd(RCC_APB1Periph_USART2,ENABLE); 3、没有端口映射 4、没有使能串口 |
学习一下 |