Search topics...
GPIOInput Configurationfoundational

What are GPIO alternate functions, and how are they configured?

0 upvotes
Practice with AISoon
Study the fundamentals first — GPIO topic page

Each GPIO pin on an STM32 can serve multiple roles beyond simple digital I/O. Alternate functions map internal peripheral signals — UART TX/RX, SPI MOSI/MISO/SCK, I2C SDA/SCL, timer channels, DAC outputs — to physical pins. Each pin typically supports up to 16 alternate function mappings (AF0 through AF15), defined in the datasheet's alternate function mapping table. The purpose is silicon flexibility: a single MCU package can support many different board layouts by allowing peripheral signals to be routed to different pins.

To configure a pin as a peripheral signal, you set three things: (1) the GPIO mode to alternate function (MODER = 0b10), (2) the correct AF number via the AFR registers (AFRL for pins 0-7, AFRH for pins 8-15), and (3) the appropriate output type, speed, and pull configuration. For example, I2C SDA requires open-drain with a pull-up; SPI SCK requires push-pull at high speed; UART TX requires push-pull at medium speed. Getting any of these wrong produces subtle bugs — a push-pull I2C SDA will appear to work with a single device but cause bus contention with two devices.

A common source of "peripheral not working" bugs is selecting the wrong AF number. The mapping is not intuitive and varies between STM32 families and even between pins on the same MCU. PA9 might be USART1_TX on AF7, but PA2 might be USART2_TX on AF7 on one chip and AF1 on another. Always verify against the datasheet's alternate function table, not from memory. STM32CubeMX prevents this class of errors by showing valid AF mappings graphically and generating the correct initialization code.

Source: GPIO Q&A