查看文档后发现是由于没有将端口映射到USART1,然后添加如下代码:
1 GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_USART1); // PB6 - TX
2 GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_USART1); // PB7 - RX
然后可以通讯了,但是数据是错误的,检查代码无误,Google了一下,原来是板子的晶振频率不对,
在 stm32f4xx.h 中默认是25M的,但是我的板子是8M的晶振,所以修改了一下该文件(去掉文件的只读权限后可修改):
1 #if !defined (HSE_VALUE)
2 #define HSE_VALUE ((uint32_t)8000000) /*!< Value of the External oscillator in Hz */ //原来是25000000
3
4 #endif /* HSE_VALUE */
修改后可以正常通讯了。
附初始化代码:
GPIO_InitTypeDef GPIO_InitStructure;
USART_InitTypeDef USART_InitStruct;
NVIC_InitTypeDef NVIC_InitStruct;
/* 使能 */
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOB, ENABLE);
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);
/* 端口映射 */
GPIO_PinAFConfig(GPIOB,GPIO_PinSource6,GPIO_AF_USART1);
GPIO_PinAFConfig(GPIOB,GPIO_PinSource7,GPIO_AF_USART1);
/* 中断初始化 */
NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 2;
NVIC_InitStruct.NVIC_IRQChannelSubPriority = 0;
NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
NVIC_Init(&NVIC_InitStruct);
/* 引脚(RX TX)初始化 */
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6; // tx
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
GPIO_InitStructure.GPIO_Pin = GPIO_Pin_7; // rx
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;
GPIO_Init(GPIOB,&GPIO_InitStructure);
/* 串口初始化 */
USART_InitStruct.USART_BaudRate = 9600;
USART_InitStruct.USART_WordLength = USART_WordLength_8b;
USART_InitStruct.USART_StopBits = USART_StopBits_1;
USART_InitStruct.USART_Parity = USART_Parity_No;
USART_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
USART_InitStruct.USART_Mode = USART_Mode_Tx | USART_Mode_Rx;
USART_Init(USART1,&USART_InitStruct);
USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);
USART_ClearFlag(USART1,USART_FLAG_TC);
USART_Cmd(USART1,ENABLE);