STM32F407串口

发布时间 2023-07-21 08:45:13作者: SymPny

#include "stm32f4xx.h"
#include "usart.h"


void My_USART1_Init(void)
{

     //GPIO结构体定义
    GPIO_InitTypeDef  GPIO_InitStructure;

     //串口结构体定义
    USART_InitTypeDef USART_InitStructure;

     //中断结构体定义
    NVIC_InitTypeDef NVIC_InitStructure;
    //使能时钟
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//使能USART1时钟
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);//使能GPIOA时钟

    //引脚映射

    GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);
    GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);

    //端口初始化

    //GPIOA9端口初始化结构体参数设置

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;

    //GPIOA9端口初始化
    GPIO_Init(GPIOA, &GPIO_InitStructure);

    //GPIOA10端口初始化结构体参数设置

    GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
    GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
    GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
    GPIO_InitStructure.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_UP;

    //GPIOA10端口初始化
    GPIO_Init(GPIOA, &GPIO_InitStructure);

     //串口初始化结构体参数设置

    USART_InitStructure.USART_BaudRate=115200;
    USART_InitStructure.USART_HardwareFlowControl=USART_HardwareFlowControl_None;
    USART_InitStructure.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;
    USART_InitStructure.USART_Parity=USART_Parity_No;
    USART_InitStructure.USART_StopBits=USART_StopBits_1;
    USART_InitStructure.USART_WordLength=USART_WordLength_8b;

    //串口初始化
    USART_Init(USART1,&USART_InitStructure);

    //串口使能
    USART_Cmd(USART1 ,ENABLE);
    //中断使能
    USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//接收非空使能

    //中断初始化结构体参数设置
    NVIC_InitStructure.NVIC_IRQChannel=USART1_IRQn;
    NVIC_InitStructure.NVIC_IRQChannelCmd=ENABLE;
    NVIC_InitStructure.NVIC_IRQChannelPreemptionPriority=1;
    NVIC_InitStructure.NVIC_IRQChannelSubPriority=1;

    //中断初始化
    NVIC_Init(&NVIC_InitStructure);
}

void USART1_IRQHandler(void)
{
    u8 res;

    //判断串口1
    if(USART_GetITStatus(USART1,USART_IT_RXNE)){

        //从串口1是否发生接收中断
        res=USART_ReceiveData(USART1);

        //通过串口1发送数据
        USART_SendData(USART1,res);
    }

}
int main(void)
{

    //中断分组使能
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);

    //串口初始化
    My_USART1_Init();
    while(1);
}