Electrical – How to assign peripherals to physical pins for STM32 MCUs

peripheral-pin-selectstm32

I'm using STM32F series MCUs with a RTOS. Since the OS provides API to configure the peripherals and their physical output assignment, I didn't pay much attention in the past. Now I want to have full control of this type of hardware configurations.

The point I've confused is that, according to datasheet, a physical pin might be in one of 3 different modes (for STM32F103, in this case):

  1. Main function (after reset)
  2. Primary alternate function (Alternate function/Default)
  3. Remapped alternate function

"Main function" is easy to understand. However, for example, one primary alternate function can be assigned to 3 different peripherals for the same physical pin:

enter image description here

Question

Where are we configuring if PA2 is used for whether USART2_TX or ADC12_IN2 or TIM2_CH3?

Best Answer

Where are we configuring if PA2 is used whether USART2_TX or ADC12_IN2 or TIM2_CH3?

Every GPIO has a Port configuration register (GPIOx_CRL/GPIOx_CRH).
The STM32F1 series also has AFIO (alternate function input output) registers with remap bits. These are per function, not per pin. See AFIO_MAPR.

The REMAP register is where things get difficult, because this remaps multiple pins.

To solve this puzzle I recommend you use the STM32Cube initialization code generator.

Is it the operating systems' or the STM's headers' responsibility generating an error message if we try to configure PA2 as both USART2_TX and ADC12_IN2?

It it physically not possible to configure PA2 as USART2_TX and ADC_IN12.

To put it in ADC_IN12, you only set CNF to Analog and MODE to input.
To put it in USART2_TX set CNF push-pull and enable alternate function.
To put it in TIM2_CH3, set CNF to floating or push-pull, enable alternate function, and enable TIM2_REMAP in AFIO_MAPR.

Analog mode has priority. This disables the digital features, such as schmitt trigger and output control.

(You might still be able to use the ADC while digital input/output functions are enabled, I have never tried this)

enter image description here

both settings for TIM2_CH3 and USART2_TX have the same configuration

That is because they require the same functionality.
REMAP configures if you use TIM or USART.