Simvik

Route a UART to its pins from the alternate-function table

Find USART2's pins and function number in the datasheet, then set MODER, AFRL, OSPEEDR and PUPDR without disturbing other pins. A medium embedded C problem…

medium · Reading datasheets and schematics · datasheets · driver · gpio

Write usart2_pins_init(), which connects USART2 to its pins on port A, working from the Datasheet excerpt below.

Find which pins carry USART2's TX and RX, and which alternate function selects it. Then put both pins in alternate-function mode with that function, make TX push-pull at high speed, and enable the pull-up on RX, as the application note asks.

Change only the bits that belong to those two pins. Everything else on port A, the debug port above all, must keep its value.

Datasheet excerpt

Alternate function mapping (datasheet, port A, excerpt)

PinAF1AF2AF5AF7AF8
PA2TIM2_CH3TIM5_CH3—USART2_TX—
PA3TIM2_CH4TIM5_CH4—USART2_RX—
PA9TIM1_CH2——USART1_TX—
PA10TIM1_CH3——USART1_RX—

GPIO registers (reference manual)

OffsetRegisterPin y occupiesValues
0x00MODERbits 2y+1:2y00 input, 01 output, 10 alternate function, 11 analog
0x04OTYPERbit y0 push-pull, 1 open-drain
0x08OSPEEDRbits 2y+1:2y00 low, 01 medium, 10 high, 11 very high
0x0CPUPDRbits 2y+1:2y00 none, 01 pull-up, 10 pull-down
0x20AFRLbits 4y+3:4y, pins 0 to 7the AF number, 0 to 15
0x24AFRHbits 4(y−8)+3:4(y−8), pins 8 to 15the AF number, 0 to 15

Reset values of port A: MODER 0xA8000000, OSPEEDR 0x0C000000, PUPDR 0x64000000 (PA13 and PA14 are the debug port, SWDIO and SWCLK).

Application note: UART pins

Use push-pull at high speed for TX. Enable the pull-up on RX, so that the line idles high (a UART's idle level) while the cable is unplugged, rather than floating and producing framing errors.

Starter code

void usart2_pins_init(void) {
}

Example tests

From reset

usart2_pins_init();
show();

Expected output:

MODER A80000A0 OTYPER 00000000 OSPEEDR 0C000020 PUPDR 64000040 AFRL 00007700 AFRH 00000000

Learn it first

More Reading datasheets and schematics problems