Skip to content
systemcoding.dev
Embedded

Set a register field with MODIFY_REG from the STM32 headers

Change one field of an STM32 peripheral register in a single read-modify-write with MODIFY_REG, clear mask first and set mask second. STM32F4 CMSIS headers.

1 min read
Summarize in AI

MODIFY_REG(REG, CLEARMASK, SETMASK) from the STM32 device headers reads the register once, clears the bits in the first mask, sets the bits of the second and writes it back. It is the safe way to change a multi-bit field, because OR-ing a new value onto the old one leaves the old bits behind. Take GPIOA pin 5, whose MODER field is two bits wide.

moder.cc
#include "stm32f4xx.h"

void pa5_as_output(void) {
    RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
    MODIFY_REG(GPIOA->MODER, GPIO_MODER_MODER5, GPIO_MODER_MODER5_0);
}

void pa5_as_analog(void) {
    MODIFY_REG(GPIOA->MODER, GPIO_MODER_MODER5, GPIO_MODER_MODER5);
}

If MODER held 0x00000800 (pin 5 set to alternate function, 10), the first call clears bits 11:10 and sets bit 10.

Text
MODER before: 0x00000800
MODER after : 0x00000400

Using |= with GPIO_MODER_MODER5_0 would have produced 0x00000C00, which is analog mode, not output. The macro is still a plain read followed by a write, so it is not atomic against an interrupt that touches the same register; wrap it in a critical section or use the bit-set-reset register for GPIO output data. It is defined in stm32f4xx.h next to SET_BIT, CLEAR_BIT and READ_REG. On families that renamed the field to MODE5, use their constant names.

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.