1. 程式人生 > >STM32—USART

STM32—USART

前言:

最近在除錯STM32L152晶片的USART配置程式,實現STM32串列埠列印功能,本文總結下STM32L152晶片USART的使用方法。

硬體平臺:STM32L152

軟體平臺:keil v5+cubeMX

函式庫:HAL庫

1:usart初始化

UART_HandleTypeDef huart3;
uint8_t rxbuf;

void MX_USART3_UART_Init(void)
{
  huart3.Instance = USART3;
  huart3.Init.BaudRate = 115200;
  huart3.Init.WordLength = UART_WORDLENGTH_8B;
  huart3.Init.StopBits = UART_STOPBITS_1;
  huart3.Init.Parity = UART_PARITY_NONE;
  huart3.Init.Mode = UART_MODE_TX_RX;
  huart3.Init.HwFlowCtl = UART_HWCONTROL_NONE;
  huart3.Init.OverSampling = UART_OVERSAMPLING_16;
 HAL_UART_Init(&huart3);
}

//串列埠gpio初始化

void HAL_UART_MspInit(UART_HandleTypeDef* huart)
{
   GPIO_InitTypeDef GPIO_InitStruct;
  if(huart->Instance==USART3)
  {

    /* Peripheral clock enable */
    __HAL_RCC_USART3_CLK_ENABLE();
    /**USART3 GPIO Configuration
    PB10     ------> USART3_TX
    PB11     ------> USART3_RX
    */
    GPIO_InitStruct.Pin = GPIO_PIN_10|GPIO_PIN_11;
    GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
    GPIO_InitStruct.Pull = GPIO_PULLUP;
    GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH;
    GPIO_InitStruct.Alternate = GPIO_AF7_USART3;;
    HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
    /* Peripheral interrupt init */
    HAL_NVIC_SetPriority(USART3_IRQn, 0, 0);
    HAL_NVIC_EnableIRQ(USART3_IRQn);
  }
}

//串列埠反初始化

void HAL_UART_MspDeInit(UART_HandleTypeDef* huart)
{
  if(huart->Instance==USART3)
  {
    /* Peripheral clock disable */
    __HAL_RCC_USART3_CLK_DISABLE();


    HAL_GPIO_DeInit(GPIOB, GPIO_PIN_10|GPIO_PIN_11);
    /* Peripheral interrupt DeInit*/
    HAL_NVIC_DisableIRQ(USART3_IRQn);
  }
}

//串列埠中斷回撥函式(響應事件)

void HAL_UART_RxCpltCallback(UART_HandleTypeDef *huart)
{
    if(huart->Instance==USART3)
    { 
        //加入處理事件
        //如:printf("\GET data!\n");
        HAL_UART_Receive_IT(&huart3,&rxbuf,1);//重新使能串列埠中斷
    }
}

在STM32L1XX_it.c中加入中斷函式

void USART3_IRQHandler(void)
{
    HAL_UART_IRQHandler(&huart3);
}

主函式示例程式碼:

int main(void)
{
    HAL_Init( ); 
    SystemClock_Config( ); 
    MX_GPIO_Init( ); 
    MX_USART3_UART_Init(); 
    HAL_UART_Receive_IT(&huart3,&rxbuf,1);//使能串列埠中斷,有串列埠中斷便進入中斷回撥函式
    while(1)
    { 
    }
}