Beetwise

STM32 GPIO MODER calculator

GPIOx_MODER holds two bits for each of the 16 pins of a port.

The two bits of pin n sit at the positions 2n and 2n + 1.

The four modes are 00 for input, 01 for output, 10 for alternate function and 11 for analog.

Try the STM32 MODER register in the bit editor

GPIOA_MODER with PA5 as an output, and the debug pins left alone. Edit the expression or select a bit to flip it.

31
30
29
28
27
26
25
24
23
22
21
20
19
18
17
16
15
14
13
12
11
10
9
8
7
6
5
4
3
2
1
0
0x28000400
hex · 32 bits
binary
0b00101000000000000000010000000000
value
671089664

The STM32 MODER register step by step

Set PA5 as an output and keep the other pins:

  1. Pin 5 uses the bits 10 and 11, because 2 times 5 is 10.
  2. The mode for an output is 01, so bit 10 takes the value 1 and bit 11 takes the value 0.
  3. The mask for bit 10 is 1 << 10, which is 0x00000400.
  4. The reset value of GPIOA_MODER is 0x28000000 on many parts, which holds PA13 and PA14 in alternate function for the debug port.
  5. Apply OR to get 0x28000400.

The two bits of each mode, and the position of each pin

The two bits of each mode, and the position of each pin
FieldBitsValueMeaning
Mode2n and 2n+100Input
Mode2n and 2n+101General purpose output
Mode2n and 2n+110Alternate function
Mode2n and 2n+111Analog
PA01 and 0-Shift a mode by 0
PA511 and 10-Shift a mode by 10
PA1327 and 2610Debug port, alternate function at reset
PA1531 and 30-Shift a mode by 30

Where the STM32 MODER register is used

A register write that clears the debug pins loses the connection to the programmer.

A driver sets one pin and keeps the other 15, so it needs a read, a change and a write.

A HAL call hides these bits, and a register write needs them exactly.

The STM32 MODER register: points to note

  • Two bits per pin, not one. The position of pin n is 2n, so pin 5 sits at bit 10.
  • Clear the field before the OR, or an old mode stays. Apply reg &= ~(3u << (2 * n)) first.
  • A write of 0 to the whole register clears PA13 and PA14, which the debug port needs.
  • MODER holds the mode alone. The speed, the pull and the output type live in other registers.

The full bit editor

The full editor holds many values, evaluates expressions across them, and reads live values from a serial port.

Open this value in the full editor

Questions about the STM32 MODER register

How do I set PA5 as an output?
Clear the bits 11 and 10, then apply OR with 1 << 10. The mode 01 marks a general purpose output.
Which bits belong to pin n?
The bits 2n and 2n + 1. Pin 0 uses the bits 1 and 0, and pin 15 uses the bits 31 and 30.
Why is the reset value not zero?
PA13 and PA14 hold the debug port in alternate function, which gives the reset value 0x28000000 on many parts.