STM32F103 GPIO registers and port manipulation
Configure a GPIO with the STM32F1 register layout and toggle a pin without modifying its neighbours.
Enable the clock and configure the pin
On STM32F1, enable the GPIO port's APB2 clock before writing its registers. Each pin has a four-bit configuration field in CRL for pins 0–7 or CRH for pins 8–15. Preserve other fields with a mask. On STM32F4 the layout instead uses MODER, OTYPER, OSPEEDR and PUPDR. Match the code to the exact device family.
Use BSRR to set and reset one or more output bits without a read-modify-write of ODR. The low half of BSRR sets bits and the high half clears them. This example uses the STM32F103 CMSIS device header for the PC13 LED found on many Blue Pill boards.
#include <stm32f1xx.h>
void led_init(void) {
RCC->APB2ENR |= RCC_APB2ENR_IOPCEN;
(void)RCC->APB2ENR;
GPIOC->BSRR = 1u << 13;
const unsigned shift = (13u - 8u) * 4u;
GPIOC->CRH = (GPIOC->CRH & ~(0xFu << shift)) | (0x2u << shift);
}
void led_on(void) { GPIOC->BSRR = 1u << (13u + 16u); }
void led_off(void) { GPIOC->BSRR = 1u << 13; }Use low-level code inside an Arduino sketch
Keep the core's startup and clock configuration when adding register code to an existing Arduino sketch. Check if pinMode(), a peripheral library or a board-specific alternate function also owns the pin. Put peripheral code behind small functions so the code that sets clocks, configures pins and handles events stays local to the peripheral.
Connect an interrupt handler
Choose the right IRQ name from the startup file for your MCU. If writing the handler directly in a C++ sketch, give that symbol C linkage and confirm in the link map that it overrides the startup file's weak default. Enable the interrupt in both the peripheral and the NVIC. Clear the pending flag using the peripheral's documented semantics before returning.
For an IRQ already handled by Arduino or HAL, use the provided callback or attachInterrupt() where supported. A short handler can record the event and let loop() do the heavy work. In the RM0008 EXTI pending register, a write of one clears the corresponding pending bit.
