How to use ALT pins on STM32?

 On STM32, “ALT pins” usually means alternate functions (AF): using a GPIO pin for USART/SPI/I²C/TIM PWM/ADC, etc. You pick the pin’s AF mapping in CubeMX (or write the GPIO registers yourself). Here’s the practical way.



The CubeMX way (recommended)

  1. Open STM32CubeMX (or CubeIDE → .ioc).

  2. Go to Pinout & Configuration.

  3. Enable the peripheral you want (e.g., USART1, SPI2, TIM3 PWM).

  4. CubeMX will assign default pins. To use “alt pins”:

    • Click the pin on the package view (e.g., PA9)

    • Choose the function you want (e.g., USART1_TX)

    • Or open the peripheral settings → GPIO Settings and select alternate pins there.

  5. In GPIO Configuration ensure:

    • Mode = Alternate Function Push-Pull (most digital AF signals)

    • Pull-up/down as needed

    • Speed set appropriately (higher for fast edges like SPI)

  6. Generate code. CubeMX will create:

    • MX_GPIO_Init()

    • HAL_UART_MspInit() / HAL_SPI_MspInit() etc. that set the AF.

Typical HAL GPIO init snippet

GPIO_InitTypeDef GPIO_InitStruct = {0}; __HAL_RCC_GPIOA_CLK_ENABLE(); GPIO_InitStruct.Pin = GPIO_PIN_9; // PA9 GPIO_InitStruct.Mode = GPIO_MODE_AF_PP; // Alternate Function, push-pull GPIO_InitStruct.Pull = GPIO_PULLUP; // depends on signal GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_VERY_HIGH; GPIO_InitStruct.Alternate = GPIO_AF7_USART1; // AF number depends on pin+peripheral HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);

The register-level idea (what you’re really doing)

For each GPIO pin you set:

  • MODER = 10b (Alternate Function mode)

  • AFRL/AFRH = AF number (0–15) for that pin

  • Optional: OTYPER (push-pull/open-drain), PUPDR, OSPEEDR

Example (PA9 = AF7):

  • PA9 is in AFRH (pins 8–15). Set AFRH bits for pin 9 to 0b0111.

Key rules (common gotchas)

  • AF mapping is pin-specific. USART1_TX might be PA9 on many parts, but could also be PB6, etc. Always check:

    • Datasheet pinout table

    • Reference Manual AF table

    • Or just trust CubeMX’s pinout tool (fastest).

  • Some functions require specific electrical mode:

    • I²C: usually Alternate Function Open-Drain + pull-ups

    • SPI/USART/TIM: usually AF Push-Pull

  • Don’t forget clocks:

    • Enable GPIO port clock (__HAL_RCC_GPIOx_CLK_ENABLE())

    • Enable peripheral clock (USART/SPI/TIM) (HAL does this in MSP init)

  • Pin conflicts: one pin can only be one AF at a time.

Quick examples

Use a different UART pin pair

  • Enable USART1

  • Choose PB6 = TX and PB7 = RX (if supported on your STM32)

  • CubeMX sets GPIO_AF7_USART1 on PB6/PB7.

Output PWM on an “alternate” timer channel pin

  • Enable TIM3 → PWM Channel 1

  • Select a pin that supports TIM3_CH1 (e.g., PA6 on many MCUs)

  • CubeMX sets the correct AF (often AF2 for TIM3, depends on chip).

评论

此博客中的热门博文

Detailed Explanation of STM32 HAL Library Clock System

How do you set up ADC (Analog-to-Digital Converter) in STM32?

How To Connect Stm32 To PC?