Skip to content
systemcoding.dev
Embedded

Configure an STM32 pin as push-pull output via MODER

Set MODER bits 11:10 to 01 and leave OTYPER at 0 to make PA5 a push-pull output on an STM32F4, using a read-modify-write that keeps other pins intact.

1 min read
Summarize in AI

Each pin on an STM32F4 port has a two-bit field in MODER: 00 input, 01 general-purpose output, 10 alternate function, 11 analog. Push-pull is the reset state of OTYPER, so turning a pin into an output is one field. PA5 is the user LED on a Nucleo-F411RE.

led.cc
#include "stm32f4xx.h"

void pa5_output(void)
{
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    (void)RCC->AHB1ENR;

    GPIOA->MODER = (GPIOA->MODER & ~GPIO_MODER_MODER5_Msk)
                 | GPIO_MODER_MODER5_0;        /* 01 = output */
    GPIOA->OTYPER &= ~GPIO_OTYPER_OT5;         /* 0 = push-pull */
}

The mask comes first so the old mode bits are cleared; ORing 01 onto an existing 10 would give 11, analog, and the pin would do nothing. The mode field for pin n sits at bits 2n+1:2n, which is why PA5 is bits 11:10.

After the mode change the pin drives whatever is in ODR, which is zero after reset, so it comes up low and the output level may glitch briefly if you set ODR afterwards. Write the level in BSRR before switching the mode when the initial state matters, for example for an active-low chip select that must not pulse. Speed is in OSPEEDR, and the register layout above is the same on the whole F4 family. Names from STM32CubeF4 V1.28 headers.

Taggedcstm32
Share

More snippets

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.