USART串口 GPIO RCC
同时启用 USART1 和 USART2。
为 GPIO 初始化生成的代码如下所示:
- void HAL_UART_MspInit(UART_HandleTypeDef* uartHandle)
- {
- GPIO_InitTypeDef GPIO_InitStruct = {0};
- RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};
- if(uartHandle->Instance==USART1)
- {
- /* USER CODE BEGIN USART1_MspInit 0 */
- /* USER CODE END USART1_MspInit 0 */
- /** Initializes the peripherals clocks
- */
- PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_USART1;
- PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
- if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
- {
- Error_Handler();
- }
- /* USART1 clock enable */
- __HAL_RCC_USART1_CLK_ENABLE();
- __HAL_RCC_GPIOA_CLK_ENABLE();
- /**USART1 GPIO Configuration
- PA9 ------> USART1_TX
- PA10 ------> USART1_RX
- */
- GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
- /* USER CODE BEGIN USART1_MspInit 1 */
- /* USER CODE END USART1_MspInit 1 */
- }
- else if(uartHandle->Instance==USART2)
- {
- /* USER CODE BEGIN USART2_MspInit 0 */
- /* USER CODE END USART2_MspInit 0 */
- /* USART2 clock enable */
- __HAL_RCC_USART2_CLK_ENABLE();
- __HAL_RCC_GPIOA_CLK_ENABLE();
- /**USART2 GPIO Configuration
- PA2 ------> USART2_TX
- PA3 ------> USART2_RX
- */
- GPIO_InitStruct.Pin = GPIO_PIN_2|GPIO_PIN_3;
- GPIO_InitStruct.Mode = GPIO_MODE_AF_PP;
- GPIO_InitStruct.Pull = GPIO_NOPULL;
- GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_LOW;
- GPIO_InitStruct.Alternate = GPIO_AF1_USART2;
- HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
- /* USER CODE BEGIN USART2_MspInit 1 */
- /* USER CODE END USART2_MspInit 1 */
- }
- }
请注意,USART1 的生成缺少以下行:
- GPIO_InitStruct.Alternate = GPIO_AF1_USART1;
因此不会作为 UART 运行。
已通过 CubeMX 6.5.0 确认
更多回帖