Nanfeng

Notes on software development, code, and curious ideas

STM32 GPIO Modes and Registers

This overview uses the STM32F407 family. Every pin has electrical limits and a list of available alternate functions in the device datasheet; a peripheral signal cannot be assigned to an arbitrary GPIO.

Example STM32 pin-function table

Enable the port clock

GPIO registers are not usable until the port’s peripheral clock is enabled. With the HAL:

1
__HAL_RCC_GPIOE_CLK_ENABLE();

Configure a pin

1
2
3
4
5
6
7
8
GPIO_InitTypeDef config = {0};
config.Pin = GPIO_PIN_2;
config.Mode = GPIO_MODE_OUTPUT_PP;
config.Pull = GPIO_NOPULL;
config.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOE, &config);

HAL_GPIO_WritePin(GPIOE, GPIO_PIN_2, GPIO_PIN_SET);

The mode register selects input, output, alternate function, or analog. Output type selects push-pull or open-drain. Pull configuration selects none, pull-up, or pull-down. Speed controls output slew capability; choosing the highest speed unnecessarily can increase power and electromagnetic interference.

For an alternate function, configure the correct AF number as well as mode, pull, type, and speed:

1
2
config.Mode = GPIO_MODE_AF_PP;
config.Alternate = GPIO_AF7_USART1;

Important registers

  • MODER selects mode.
  • OTYPER selects output driver type.
  • OSPEEDR selects output speed.
  • PUPDR selects pulls.
  • IDR reads input state and ODR reflects output data.
  • BSRR atomically sets and resets output bits.
  • AFRL and AFRH select alternate functions.
  • LCKR can lock configuration until reset under defined conditions.

Use BSRR for concurrent bit updates instead of a read-modify-write on ODR. “5 V tolerant” applies only to explicitly marked pins and under datasheet conditions; it does not mean every mode, analog input, or unpowered state safely accepts 5 V.

+