【STM32】STM32串口配置的一般步驟(庫函數)


STM32串口配置的一般步驟(庫函數)
(1)串口時鍾使能:RCC_APBxPeriphClockCmd();
    GPIO時鍾使能:RCC_AHBxPeriphClockCmd();
(2)引腳復用映射:GPIO_PinAFConfig();
(3)GPIO端口模式配置:GPIO_Init(); 模式配置為GPIO_Mode_AF
(4)串口參數初始化:USART_Init();
(5)開啟中斷並且初始化NVIC(如果需要開啟中斷才需要這個步驟)
    NVIC_Init();
    USART_ITConfig();
(6)使能串口:USART_Cmd();
(7)編寫中斷處理函數:USARTx_IRQHandler();
(8)串口數據收發:
    void USART_SendData();//發送數據到串口,DR
    uint16_t USART_ReceiveData();//接收數據,從DR讀取接收的數據
(9)串口傳輸狀態獲取:
    FlagStatus USART_GetFlagStatus();
    void USART_ClearITPendingBit();

范例代碼:

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

/* 中斷服務函數 */
void USART1_IRQHandler(void)
{
    uint16_t recv;
 
    if (USART_GetFlagStatus(USART1,USART_IT_RXNE))
    {
        recv = USART_ReceiveData(USART1);
        USART_SendData(USART1,recv);
    }
}


void Usart1_Demo_Init(void)
{
    GPIO_InitTypeDef GPIOA_InitStruct;
    USART_InitTypeDef USART1_InitStruct;
    NVIC_InitTypeDef NVIC_InitStruct;

    RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1, ENABLE); /* 使能USART1時鍾 */
    RCC_AHB1PeriphClockCmd(RCC_AHB1Periph_GPIOA, ENABLE);  /* 使能GPIOA的時鍾 */

    /* 將PA9和PA10映射到串口1 */
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource9, GPIO_AF_USART1);
    GPIO_PinAFConfig(GPIOA, GPIO_PinSource10, GPIO_AF_USART1);

    /* 設置GPIO端口模式 */
    GPIOA_InitStruct.GPIO_Pin = GPIO_Pin_9 | GPIO_Pin_10;
    GPIOA_InitStruct.GPIO_Mode = GPIO_Mode_AF;
    GPIOA_InitStruct.GPIO_OType = GPIO_OType_PP;
    GPIOA_InitStruct.GPIO_PuPd = GPIO_PuPd_UP;
    GPIOA_InitStruct.GPIO_Speed = GPIO_Speed_100MHz;
    GPIO_Init(GPIOA, &GPIOA_InitStruct);

    /* 串口參數初始化 */
    USART1_InitStruct.USART_BaudRate = 115200;
    USART1_InitStruct.USART_HardwareFlowControl = USART_HardwareFlowControl_None;
    USART1_InitStruct.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;
    USART1_InitStruct.USART_Parity = USART_Parity_No;
    USART1_InitStruct.USART_StopBits = USART_StopBits_1;
    USART1_InitStruct.USART_WordLength = USART_WordLength_8b;
    USART_Init(USART1, &USART1_InitStruct);

    /* 使能USART1 */
    USART_Cmd(USART1, ENABLE);

    /* 使能串口使用的中斷 */
    NVIC_InitStruct.NVIC_IRQChannel = USART1_IRQn;
    NVIC_InitStruct.NVIC_IRQChannelCmd = ENABLE;
    NVIC_InitStruct.NVIC_IRQChannelPreemptionPriority = 1;
    NVIC_InitStruct.NVIC_IRQChannelSubPriority = 1;
    NVIC_Init(&NVIC_InitStruct);
    USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
}

int main(void)
{
    /* 設置中斷分組 */
    NVIC_PriorityGroupConfig(NVIC_PriorityGroup_2);
    Usart1_Demo_Init();

    while (1);
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM