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)
-
Open STM32CubeMX (or CubeIDE → .ioc).
-
Go to Pinout & Configuration.
-
Enable the peripheral you want (e.g., USART1, SPI2, TIM3 PWM).
-
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.
-
-
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)
-
-
Generate code. CubeMX will create:
-
MX_GPIO_Init() -
HAL_UART_MspInit()/HAL_SPI_MspInit()etc. that set the AF.
-
Typical HAL GPIO init snippet
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_USART1on 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).
.jpg)
评论
发表评论