Skip to content
systemcoding.dev
Embedded

Blink an LED on STM32 by Writing GPIO Registers Directly

Blink the LD2 LED on a NUCLEO-F446RE by writing the GPIO registers yourself: MODER, OTYPER, OSPEEDR, PUPDR and ODR, with a SysTick delay and a register decoder.

6 min read
Summarize in AI
Flat illustration of a hardware register drawn as bit fields with one field highlighted, with the STMicroelectronics, Arm and C logos.

Every STM32 GPIO port has the same small set of registers, and an LED blink uses all of them in a few lines. Knowing what each register does, and what the reset value is, makes every later peripheral easier, because the alternate-function, interrupt and analogue modes are all more settings in the same registers. This post blinks the green LED (LD2) on a NUCLEO-F446RE board by writing the GPIOA registers directly, with no HAL and no CMSIS peripheral drivers, using only the register definitions from the CMSIS device header. The LED sits on pin PA5. The program uses the SysTick timer for a delay instead of a counting loop, so the blink rate is a property of the clock and not of the compiler. The board and register layout come from the STM32F446 reference manual RM0390.

The port registers

Each GPIO port (A, B, C and so on) has the same ten registers at fixed offsets from the port's base address. Five of them configure a pin and one controls its output:

RegisterOffsetBits per pinWhat it sets
MODER0x002Mode: 00 input, 01 output, 10 alternate function, 11 analogue
OTYPER0x041Output type: 0 push-pull, 1 open-drain
OSPEEDR0x082Output slew rate: low, medium, high, very high
PUPDR0x0C2Pull resistors: 00 none, 01 pull-up, 10 pull-down
IDR0x101Input data (read-only): the pin level
ODR0x141Output data: the level to drive
BSRR0x181 + 1Set (low half) and reset (high half) bits atomically

MODER uses two bits per pin, so pin N occupies bits 2N+1 and 2N. For PA5 that is bits 11:10. The reset state is input mode (00) for most pins, with the exception of the debug pins on port A (PA13, PA14, PA15) and PB3 and PB4, which reset in alternate function mode for the debug interface.

Before any of this works, the port's clock must be on. On the STM32F4 the GPIO ports are on the AHB1 bus, with one enable bit per port in RCC_AHB1ENR: GPIOA is bit 0.

The program

blink_nucleo.cc
#include <stdint.h>
#include "stm32f446xx.h"

#define LED_PIN 5u

static volatile uint32_t ticks;

void SysTick_Handler(void)
{
	ticks++;
}

static void delay_ms(uint32_t ms)
{
	uint32_t start = ticks;

	while ((ticks - start) < ms)
		;
}

int main(void)
{
	/* 1. Clock to GPIOA, then a read-back so the write has taken effect */
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
	(void)RCC->AHB1ENR;

	/* 2. PA5: output, push-pull, low speed, no pull */
	GPIOA->MODER   = (GPIOA->MODER   & ~(3u << (LED_PIN * 2))) | (1u << (LED_PIN * 2));
	GPIOA->OTYPER &= ~(1u << LED_PIN);
	GPIOA->OSPEEDR &= ~(3u << (LED_PIN * 2));
	GPIOA->PUPDR   &= ~(3u << (LED_PIN * 2));

	/* 3. 1 ms tick from the 16 MHz HSI the chip runs at after reset */
	SysTick->LOAD = 16000u - 1u;
	SysTick->VAL  = 0;
	SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk
	              | SysTick_CTRL_TICKINT_Msk
	              | SysTick_CTRL_ENABLE_Msk;

	for (;;) {
		GPIOA->ODR ^= (1u << LED_PIN);
		delay_ms(500);
	}
}

It needs a startup file and linker script as in the bare-metal blinky post; the vector table must include SysTick_Handler at entry 15.

Line by line

Step 1. Enabling the clock and reading the register back is the sequence the reference manual and ST's errata recommend: there is a short delay between setting the enable bit and the port responding, and a read of the register after the write takes at least that long.

Step 2. Each register write uses a mask-and-set on the pin's own bits, so other pins on port A, including the debug pins, are untouched. Writing MODER = 1u << 10 would set PA5 to output and reset every other pin on the port to input mode, including PA13 and PA14, which would disable the debug connection. The read-modify-write pattern avoids that. OTYPER 0 selects push-pull, which drives the LED high and low. OSPEEDR low speed is the right choice for a signal that changes twice a second, since faster edges only add noise. PUPDR no-pull is correct for an output.

Step 3. After reset the STM32F446 runs from the 16 MHz HSI. SysTick counts down from LOAD to zero and interrupts, so a reload of 16 000 minus one gives an exactly 1 ms period at 16 MHz. The CLKSOURCE bit selects the processor clock for the counter rather than the clock divided by 8. The tick counter is volatile because the interrupt handler changes it behind the main loop's back.

The loop. ODR ^= bit is a read-modify-write: it reads the output register, flips the bit and writes it back. That is fine here because only the main loop touches port A's output register. If an interrupt also wrote ODR, the read-modify-write could lose an update. The next post of this cluster uses BSRR for that reason.

delay_ms computes the elapsed ticks as ticks - start in unsigned arithmetic, which stays correct across the 32-bit wrap of the counter, after about 49 days at 1 ms.

What the registers look like afterwards

In the debugger after the first loop iteration:

Text
(gdb) print/x GPIOA->MODER
(gdb) print/x GPIOA->ODR
Text
$1 = 0xa8000400
$2 = 0x20

MODER = 0xA8000400 has three groups of bits. Bits 11:10 are 01, which is 0x400, so PA5 is an output. Bits 27:26 hold 10 (PA13, SWDIO) and bits 29:28 hold 10 (PA14, SWCLK), and bits 31:30 hold 10 (PA15, JTDI), which together make 0xA8000000: those three pins are still in alternate function mode for the debugger, as the reset value requires. This confirms that the read-modify-write did not disturb them. ODR = 0x20 is bit 5 set: the LED is on at that moment, and the value alternates between 0x20 and 0x00 every 500 ms.

The same thing with a decoder

A short helper that turns the register into words makes the bits easier to read while you learn:

c
const char *mode_name(uint32_t moder, unsigned pin)
{
	static const char *names[4] = {"input", "output", "alternate", "analog"};

	return names[(moder >> (pin * 2)) & 3u];
}

mode_name(GPIOA->MODER, 5) returns "output", and mode_name(GPIOA->MODER, 13) returns "alternate". Calling it from a console during development catches the usual mistake of configuring the wrong pin number or forgetting the clock, because the mode reads back as input when the write was ignored.

SymptomCheck
LED never lightsClock enable missing: read RCC->AHB1ENR bit 0; MODER bits stay 00
LED always dimPin in input mode with a leakage path; MODER not written
Blinks too fast or slowSysTick->LOAD assumes 16 MHz; a different clock needs a different reload
Debugger loses the targetMODER was assigned instead of modified, putting PA13 and PA14 in input mode
Does not compileThe device header name must match the part: stm32f446xx.h for the F446

The LED on the Nucleo-64 boards is on PA5 for the F4 and F0 families, but other Nucleo boards (the Nucleo-144 and the L4 and H7 variants) use different pins and sometimes active-low wiring. Read the board's user manual for the LED pin.

Doing the same with BSRR

The toggle in the loop reads ODR, flips a bit and writes it back. The same blink with BSRR needs a small amount of state, since BSRR cannot be read. Keep the LED state in a variable and write the set or reset bit:

c
static int led_on;

static void led_toggle(void)
{
	led_on = !led_on;
	GPIOA->BSRR = led_on ? (1u << LED_PIN) : (1u << (LED_PIN + 16u));
}

The write touches only PA5, whatever else changes on the port, which is the property the next post in this cluster builds on. For a single LED in a program with no interrupts the two forms behave the same, so use whichever you find clearer, and switch to BSRR the day a second context starts writing the port.

Share

Keep reading

Get new posts by email

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

Unsubscribe in one click. No spam, ever.