我最近在学习stm32单片机 在用 stm32f401re 进行usart1串口通信时候 一直无法接受到数据 还望大佬们指点迷津 以下为我的代码
经查询stm32f401re数据手册 发现PA9 PA10 分别是USART1_TX 与 USART1_RX 的复用端口
#include "stm32f4xx.h"
#include "Delay.h"
void system_init(void)
{
NVIC_InitTypeDef NVIC_InitStructure;
GPIO_InitTypeDef GPIO_InitStruct;
USART_InitTypeDef USART_InitStruct;
RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE);
RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);
GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1); // Tx
GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1); // Rx
GPIO_InitStruct.GPIO_Pin = GPIO_Pin_10 | GPIO_Pin_9;
GPIO_InitStruct.GPIO_Mode = GPIO_Mode_AF;
GPIO_InitStruct.GPIO_OType = GPIO_OType_PP; //推挽复用输出
GPIO_InitStruct.GPIO_PuPd = GPIO_PuPd_UP; //上拉
GPIO_InitStruct.GPIO_Speed = GPIO_Speed_50MHz;
GPIO_Init(GPIOA, &GPIO_InitStruct);
USART_InitStruct.USART_BaudRate = 9600; //波特率设置
USART_InitStruct.USART_WordLength = USART_WordLength_8b; //字长为8位数据格式
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_Rx | USART_Mode_Tx; //收发模式
USART_Init(USART1, &USART_InitStruct); //初始化串口1
USART_Cmd(USART1, ENABLE);
// USART_ClearFlag(USART1, USART_FLAG_TC);
USART_ITConfig(USART1, USART_IT_RXNE, ENABLE); //开启相关中断
// Usart1 NVIC 配置
NVIC_InitStructure.NVIC_IRQChannel = USART1_IRQn; //串口1中断通道
NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority = 3; //抢占优先级3
NVIC_InitStructure.NVIC_IRQChannelSubPriority = 3; //子优先级3
NVIC_InitStructure.NVIC_IRQChannelCmd = ENABLE; // IRQ通道使能
NVIC_Init(&NVIC_InitStructure);
}
void USART1_IRQHandler(void) //串口1中断服务程序
{
u8 r;
if (USART_GetITStatus(USART1, USART_IT_RXNE) != RESET) //接收中断
{
r = USART_ReceiveData(USART1); //(USART1->DR); //读取接收到的数据
USART_SendData(USART1, r);
while (USART_GetFlagStatus(USART1, USART_FLAG_TC) != SET)
;
}
USART_ClearFlag(USART1, USART_FLAG_TC);
}
int main()
{
NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2); //中断优先级分组 分2组
system_init();
}
问题是一直无法接受数据
还望懂的大佬指点 感谢! |