STM32F4 5.STM32F4串口通讯

1.串口配置步骤

  1.1 串口时钟使能(RCC_APBxPeriphClockCmd()),GPIO口使能(RCC_AHP1PeriphClockCmd())

  1.2 引脚复用映射(GPIO_PinAFConfig())

  1.3 GPIO口模式设置为复用,初始化GPIO口(GPIO_Mode_AF, GPIO_Init())

  1.4 串口初始化(USART_Init())

  1.5 开启串口中断并初始化NVIC(如要开启中断才需要此步骤)

    NVIC_Init();

    USART_ITConfig();

  1.6 使能串口(USART_Cmd())

  1.7 编写中断处理函数

    USART_IRQHandler();

  1.8 串口数据收发

    串口数据接收(void USART_ReceiveData())

    串口数据发送(uint16 USART_SendData())

  1.9 串口传输状态获取

    FlagStatus USART_GetFlagStatus()

    void USART_ClearTPendingBit()

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


void USART1_Init(void)
{
        GPIO_InitTypeDef GPIO_InitStruct_A;
        USART_InitTypeDef USART_InitStruct_1;
        NVIC_InitTypeDef NVIC_InitStruct;
    
    //1.1 串口时钟使能,GPIO口使能
    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1,ENABLE);//串口时钟使能
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA,ENABLE);//GPIO口使能,串口1对应的GPOIOA9和10,所以使能GPIOA
    
    //1.2 引脚复用映射
    GPIO_PinAFConfig(GPIOA,GPIO_PinSource9,GPIO_AF_USART1);//GPIO口复用
    GPIO_PinAFConfig(GPIOA,GPIO_PinSource10,GPIO_AF_USART1);//GPIO口复用
    
    //1.3 GPIO口模式设置为复用,初始化GPIO口
    GPIO_InitStruct_A.GPIO_Pin=GPIO_Pin_9|GPIO_Pin_10;//PA9 PA10
    GPIO_InitStruct_A.GPIO_OType=GPIO_OType_PP;//推挽
    GPIO_InitStruct_A.GPIO_Mode=GPIO_Mode_AF;//复用
    GPIO_InitStruct_A.GPIO_PuPd=GPIO_PuPd_UP;//上拉
    GPIO_InitStruct_A.GPIO_Speed=GPIO_Speed_100MHz;//频率100mhz
    GPIO_Init(GPIOA,&GPIO_InitStruct_A);
    
    //1.4串口初始化
    USART_InitStruct_1.USART_BaudRate=115200;//波特率
    USART_InitStruct_1.USART_HardwareFlowControl=USART_HardwareFlowControl_None;//硬件流控制
    USART_InitStruct_1.USART_Mode=USART_Mode_Rx|USART_Mode_Tx;//模式(发送和接收)
    USART_InitStruct_1.USART_Parity=USART_Parity_No;//奇偶校验
    USART_InitStruct_1.USART_StopBits=USART_StopBits_1;//一个停止位
    USART_InitStruct_1.USART_WordLength=USART_WordLength_8b;//8个字长
    
    USART_Init(USART1,&USART_InitStruct_1);//初始化串口
    USART_Cmd(USART1,ENABLE);//串口使能
    
    //1.4 开启串口中断并初始化NVIC
    USART_ITConfig(USART1,USART_IT_RXNE,ENABLE);//使能串口中断
    NVIC_InitStruct.NVIC_IRQChannel=USART1_IRQn;//串口1对应通道
    NVIC_InitStruct.NVIC_IRQChannelCmd=ENABLE;//使能通道
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority=1;//抢占优先级1
    NVIC_InitStruct.NVIC_IRQChannelSubPriority=1;//响应优先级1
    NVIC_Init(&NVIC_InitStruct);//初始化NVIC
}

//中断处理函数
void USART1_IRQHandler(void)
{
    u8 u8Receive;//接收到的数据
    if(USART_GetITStatus(USART1,USART_IT_RXNE))//判断是否是串口1 接收数据触发中断(USART_IT_RXNE)
    {
        u8Receive=USART_ReceiveData(USART1);
        USART_SendData(USART1,u8Receive);//发送接收到的函数
    }
}

int main(void)
{
    
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);//中断分组
    USART1_Init();//初始化串口
    while(1);
}

 

你可能感兴趣的:(STM32F4 5.STM32F4串口通讯)