User Tools

Site Tools

blog:2020-02-06_stm32_stdlib_usart1_initialization



2020-02-06 STM32 StdLib USART1 Initialization

  • The program piece is my STM32 USART1 Initialization part.
  • The PA9 & PA10 are the used pins for USART1.

Program

  • void Uart1Port_Initialize()
    {
      // 宣告 USART、GPIO 結構體 ------->
      USART_InitTypeDef USART_InitStructure;
      GPIO_InitTypeDef GPIO_InitStructure;
      // <-------
    
      // 啟用 USART1, AFIO 的 RCC 時鐘 ------->
      RCC_APB2PeriphClockCmd(RCC_APB2Periph_USART1 | 
                             RCC_APB2Periph_AFIO | 
                             RCC_APB2Periph_GPIOA, ENABLE);
      // <-------
      
      // USART1 GPIO config ------->
      // GPIOA PIN9 alternative function Tx 
      GPIO_InitStructure.GPIO_Pin = GPIO_Pin_9;
      GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
      GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF_PP;
      GPIO_Init(GPIOA, &GPIO_InitStructure);
      // GPIOA PIN9 alternative function Rx 
      GPIO_InitStructure.GPIO_Pin = GPIO_Pin_10;
      GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
      GPIO_InitStructure.GPIO_Mode = GPIO_Mode_IN_FLOATING;
      GPIO_Init(GPIOA, &GPIO_InitStructure);
      // <-------
      
      // USART 基本參數設定 ------>
      // 設定 USART 包率 (每秒位元數) 為 115200
      USART_InitStructure.USART_BaudRate = 115200; 
      // 設定 USART 傳輸的資料位元為 8
      USART_InitStructure.USART_WordLength = USART_WordLength_8b; 
      // 設定 USART 停止位元為 1
      USART_InitStructure.USART_StopBits = USART_StopBits_1;
      // 不使用同位元檢查
      USART_InitStructure.USART_Parity = USART_Parity_No; 
      // 不使用流量控制
      USART_InitStructure.USART_HardwareFlowControl = USART_HardwareFlowControl_None; 
      // 設定 USART 模式為 Rx (接收) 、 Tx (傳送)
      USART_InitStructure.USART_Mode = USART_Mode_Rx | USART_Mode_Tx;  
      // 套用以上 USART 設置,並初始化UART1
      USART_Init(USART1, &USART_InitStructure); 
      // <-------
      
      // 啟用 USART1 ------->
      USART_Cmd(USART1, ENABLE);
      // <------
      
      // Enable RXNE interrupt ------->
      USART_ITConfig(USART1, USART_IT_RXNE, ENABLE);
      // <------
      
      // Enable USART1 global interrupt ------->
      NVIC_EnableIRQ(USART1_IRQn);
      // <-------
    }
    
    void USART1_IRQHandler(void)
    {
        // RXNE handler ------>
        if(USART_GetITStatus(USART1, USART_IT_RXNE) != RESET)
        {
            if((char)USART_ReceiveData(USART1) == 'a')
            {
                USART_SendData(USART1, 'A');
                // Wait until Tx data register is empty, not really 
                // required for this example but put in here anyway.
            }
        }
        // <------
    }  
    

TAGS

  • 360 person(s) visited this page until now.

Permalink blog/2020-02-06_stm32_stdlib_usart1_initialization.txt · Last modified: 2020/02/06 20:47 by jethro

oeffentlich