Skip to content
systemcoding.dev
Embedded

The Complete Guide to GPIO on Microcontrollers

Learn GPIO from the pin up: modes, pull resistors, drive strength, interrupts, debouncing, alternate functions and loads, with STM32 code and cross-chip notes.

27 min read
Summarize in AI
Flat illustration of a microcontroller wired to an LED and a sensor, with the Arm, C and STMicroelectronics logos.

A general-purpose input/output pin, GPIO, is the first thing you meet on a microcontroller and the thing you keep using for as long as you write firmware. It turns an LED on, reads a button, selects a chip on a bus, wakes the chip from sleep and, with one register change, becomes the TX line of a UART. It looks simple because the software interface is simple: set a bit, read a bit. What is under that bit decides whether your LED is bright, your button works, your I2C bus functions and your chip survives. This guide goes from the electrical structure of one pin up to the software patterns that use it. It uses an STM32F407 for the register-level examples, compiled with arm-none-eabi-gcc 13.2 against CMSIS 5 headers, and the register layout comes from the reference manual RM0090. The ideas carry unchanged to AVR, RP2040, ESP32 and nRF52, and a comparison section shows how each names the same features.

It assumes you know what a voltage and a current are, and nothing about microcontrollers. Every term is defined as it appears. The posts that follow in this cluster take individual topics deeper, such as the BSRR register, debouncing, alternate-function mapping and pull-up choice. This guide is the map that shows where each one fits.

What a pin is made of

A microcontroller pin is a small circuit connected to the outside world through a metal pad. A typical GPIO, drawn in the reference manual as the "basic structure of an I/O port bit", contains:

BlockRole
Protection diodesTwo diodes, one to the supply and one to ground, clamp voltages outside the supply range
Pull-up and pull-down resistorsSwitchable resistors that give a defined level to a pin nothing is driving
Input buffer with Schmitt triggerTurns the pin voltage into a clean 0 or 1, with hysteresis so slow or noisy edges do not chatter
Output driverA pair of transistors that drive the pin high and low
MultiplexerChooses whether the pin belongs to the GPIO logic or to a peripheral such as a UART
RegistersThe bits software uses to configure and control all of the above

Everything the software does with a GPIO is a setting on one of these blocks, and every GPIO problem is an electrical fact about one of them. Keep the picture in mind: the pin is not a wire to the CPU, it is a configurable interface.

The two diodes explain a rule worth stating early. A pin voltage above the supply or below ground forward-biases a diode and pushes current into the chip's supply or ground, which can latch up or damage it. The datasheet's absolute maximum ratings give the limits: for most 3.3 V STM32 pins, a voltage no higher than VDD plus 4 V on 5 V tolerant pins, and a small injected current per pin. A pin that must meet a higher voltage needs a resistor, a divider or a level shifter.

The two directions

Input

An input pin reads the voltage and reports a bit. Whether that voltage counts as 0 or 1 is defined by two thresholds in the datasheet: VIL, the highest voltage still read as low, and VIH, the lowest voltage read as high. For a 3.3 V STM32 the figures are about 0.3 times VDD for VIL and 0.7 times VDD for VIH on the standard I/O, which is the CMOS rule of thumb. Between them the reading is undefined; the Schmitt trigger gives hysteresis, meaning the rising and falling thresholds differ, so a signal that creeps slowly through the zone toggles once and not many times.

An input pin draws almost no current, a leakage of the order of a microamp, so it can sit on a high-impedance signal without loading it. That is also why a disconnected input floats: with nothing to define its voltage it picks up whatever charge the environment gives it, and reads 0, 1 or oscillates. The remedy is a pull resistor, discussed below.

Output

An output pin drives its level with transistors. In the standard push-pull configuration, one transistor connects the pin to VDD when the output bit is 1 and another connects it to ground when it is 0. The pin can therefore source current (push it out when high) and sink current (pull it in when low).

The amount is limited. A datasheet lists, for each pin, the output voltage drops at stated currents, for example VOL at 8 mA sinking and VOH at 8 mA sourcing, and an absolute maximum per pin and for the whole package. On the STM32F4, the per-pin limit is 25 mA and the total across the supply pins is limited as well. At light loads the pin is close to the rails; at heavy loads the output voltage droops, which can turn an LED dim or a logic level invalid. A pin is a signal, not a power supply, and a load that draws tens of milliamperes needs a transistor, as a later section shows.

The modes

The mode of a pin is a setting, and it is the first one to get right. A simplified view, with the STM32F4 register encoding in the last column:

ModeDirectionWhat it doesMODER / other
Input, floatingInReads the pin, no resistorMODER = 00, PUPDR = 00
Input, pull-upInReads the pin, resistor to VDDMODER = 00, PUPDR = 01
Input, pull-downInReads the pin, resistor to groundMODER = 00, PUPDR = 10
AnalogueBothInput buffer off, pad connected to ADC or DACMODER = 11
Output, push-pullOutDrives high and lowMODER = 01, OTYPER = 0
Output, open-drainOutDrives low, releases for highMODER = 01, OTYPER = 1
Alternate functionBothPin belongs to a peripheralMODER = 10, AFR selects which

On the STM32F4 every port, such as GPIOA, has these registers, each field per pin:

RegisterBits per pinPurpose
MODER2Mode, as in the table
OTYPER1Output type, push-pull or open-drain
OSPEEDR2Output slew rate (low, medium, high, very high)
PUPDR2Pull-up or pull-down
IDR1Input data, read-only
ODR1Output data
BSRR1 + 1Atomic set and reset of ODR bits
LCKR1 + keyLock the configuration
AFRL, AFRH4Alternate-function number

The reset state of most pins is analogue or floating input, which draws the least power and is safe when the pin is connected to anything. The exceptions are the debug pins (PA13, PA14, PA15, PB3, PB4 on many STM32s), which reset in alternate function so the debugger can connect.

Your first output: an LED

Before any pin works, its port's clock must be on, because on an STM32 peripherals ignore writes while their clock gate is off. Then configure the pin and drive it. PD12 is the green LED on the STM32F4DISCOVERY board:

led.cc
#include <stdint.h>
#include "stm32f407xx.h"

void led_init(void)
{
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIODEN;
	(void)RCC->AHB1ENR;

	GPIOD->MODER   = (GPIOD->MODER   & ~(3u << 24)) | (1u << 24);    /* output */
	GPIOD->OTYPER &= ~(1u << 12);                                     /* push-pull */
	GPIOD->OSPEEDR &= ~(3u << 24);                                    /* low speed */
	GPIOD->PUPDR   &= ~(3u << 24);                                    /* no pull */
}

void led_on(void)  { GPIOD->BSRR = (1u << 12); }
void led_off(void) { GPIOD->BSRR = (1u << (12 + 16)); }

The MODER write uses the read-modify-write pattern: clear the two bits for this pin, then set the new value, leaving every other pin of the port alone. Assigning the register whole would reset all the other pins, including any debug pins, to input. led_on and led_off use BSRR, the register that sets and clears pins in one store, so an interrupt that changes another pin of port D at the same moment cannot lose either update.

Sizing the resistor

An LED has a roughly constant forward voltage when lit (about 2 V for red, higher for blue and white) and its brightness follows the current. A resistor in series sets the current: R = (VDD - V_F) / I. For a red LED with V_F = 2.0 V on a 3.3 V pin at 5 mA, R = (3.3 - 2.0) / 0.005 = 260 ohm, so a 270 ohm resistor from the standard series. The pin sources 5 mA, well under its limit. A host-side check of a few combinations:

ledcalc.cc
#include <stdio.h>

int main(void)
{
	double vdd = 3.3;
	double vf[] = { 1.8, 2.0, 3.0 };
	double target_ma = 5.0;

	for (int i = 0; i < 3; i++) {
		double r = (vdd - vf[i]) / (target_ma / 1000.0);
		printf("Vf %.1f V at %.0f mA -> %.0f ohm\n", vf[i], target_ma, r);
	}
	return 0;
}
Text
Vf 1.8 V at 5 mA -> 300 ohm
Vf 2.0 V at 5 mA -> 260 ohm
Vf 3.0 V at 5 mA -> 60 ohm

A blue LED with a forward voltage near 3 V on a 3.3 V supply leaves only 0.3 V across the resistor and is a poor fit for a 3.3 V pin: the current varies widely with small changes in forward voltage. Drive such an LED from a higher rail through a transistor.

Your first input: a button

Wire a pushbutton between the pin and ground, and enable the internal pull-up so the pin reads 1 when the button is open and 0 when it is pressed:

button.cc
void button_init(void)
{
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;
	(void)RCC->AHB1ENR;

	GPIOA->MODER &= ~(3u << 0);                                       /* PA0 input */
	GPIOA->PUPDR  = (GPIOA->PUPDR & ~(3u << 0)) | (1u << 0);          /* pull-up */
}

int button_pressed(void)
{
	return !(GPIOA->IDR & 1u);
}

This is the active-low convention: pressed is 0. The Discovery board's user button is wired the other way, active high with an external pull-down, so its test is GPIOA->IDR & 1. Always check the schematic for the polarity of the board you have. The signal here is read in a loop, which is called polling, and works for anything that does not need an instant reaction.

Pull resistors and what to choose

A pull resistor defines the idle level. The internal ones on the STM32F4 are 30 to 50 kilohm, per the datasheet, weak enough that a switch to ground overpowers them and strong enough to hold a short, quiet wire. For long cables, I2C and strapping pins an external resistor is the better choice, and a dedicated post in this cluster has the comparison, including how to compute the current a pull-up wastes when the input is held low (VDD divided by R: 3.3 V across 40 kilohm is 83 microamps).

The pull direction follows from the safe state. A button to ground with a pull-up reads released if the wire breaks. A button to VDD with a pull-down also reads released. Choose the polarity in which the failure you worry about gives the harmless reading.

Push-pull and open-drain

In push-pull mode the pin drives both levels. In open-drain mode it drives only low and releases the line for high, relying on a pull-up resistor to bring it up. Open-drain is the right choice when several devices share a line (I2C, 1-Wire, shared interrupt requests), when the high level should be a different voltage from the chip's supply (a pull-up to 5 V on a 5 V tolerant pin), or when a line may be pulled low by anyone. Push-pull is right for everything else, because its edges are fast and symmetric. Never connect two push-pull outputs to the same wire: if one drives high and the other low, the transistor pair shorts VDD to ground through the wire.

c
GPIOD->OTYPER |= (1u << 12);        /* PD12 open-drain */

The register value is a single bit, and the electrical difference is large. The full explanation, with I2C as the example, is in the push-pull versus open-drain post of this cluster.

Output speed and why not to max it out

OSPEEDR sets the slew rate, how fast the output edges rise and fall. The settings range from low to very high, and the datasheet gives, for each, the maximum toggle frequency for a given capacitive load: for example a few megahertz at low speed and up to 100 MHz at very high speed with 30 pF on an STM32F4 at 3.3 V.

The tempting choice is the highest setting always. The cost is real: fast edges contain high-frequency energy that radiates, rings on long traces and couples into neighbouring signals, and they cause larger supply current spikes when many pins switch together. The right setting is the slowest one that meets the signal's timing. An LED, a relay driver and a button input need low. A 1 MHz SPI clock needs medium. A 42 MHz SPI clock needs high or very high. Choosing by need lowers electromagnetic emissions and often fixes mysterious noise problems at no cost.

Driving loads bigger than a pin

A pin can supply milliamperes. Many loads need more: a relay coil takes tens of milliamperes, a motor hundreds, a strip of LEDs amperes. The solution is a transistor that the pin controls and the supply feeds. An NPN transistor or a logic-level N-channel MOSFET, with its source (or emitter) to ground, the load between the supply and its drain (or collector), and the pin driving the gate (or the base through a resistor) works for most small loads.

c
void relay_set(int on)
{
	if (on)
		GPIOB->BSRR = (1u << 3);            /* PB3 high turns the transistor on */
	else
		GPIOB->BSRR = (1u << (3 + 16));
}

Two protections matter for inductive loads such as relays and motors. A flyback diode across the coil gives the current a path when the transistor turns off, because the collapsing field would otherwise create a voltage spike many times the supply that destroys the transistor and can reach the pin. And a pull-down resistor on the gate keeps the transistor off while the pin is in its power-up input state, so the relay does not pulse during reset. A pin at reset is an input and floats; a load that must not move needs that resistor.

Reading several pins at once

The input data register holds the whole port, so reading eight related pins is one load and a shift. A keypad matrix or a parallel bus uses it:

c
uint8_t read_nibble(void)
{
	return (GPIOE->IDR >> 8) & 0xFu;          /* PE8..PE11 as a 4-bit value */
}

A scan of a 4 by 4 keypad drives each row low in turn (as open-drain or push-pull outputs) and reads the columns with pull-ups, which is a loop around two port reads. The same register works for writing groups through BSRR, with the set bits in the low half and the clear bits in the high half of one 32-bit store, so that all the lines change in the same bus cycle.

c
void write_nibble(uint8_t v)
{
	uint32_t set = (uint32_t)(v & 0xFu) << 8;
	uint32_t clr = (uint32_t)(~v & 0xFu) << 8;

	GPIOE->BSRR = set | (clr << 16);
}

Interrupts from pins

Polling wastes the CPU and can miss short pulses. A pin can instead raise an interrupt on a level or an edge, and the core runs a handler when it happens. On the STM32 this goes through the external interrupt controller, EXTI, which has lines 0 to 15, one per pin number. The port that line N listens to is chosen in SYSCFG_EXTICRx: line 0 can be PA0, PB0, PC0 and so on, one at a time. A falling-edge interrupt on PA0:

exti.cc
#include "stm32f407xx.h"

volatile uint32_t pressed_count;

void exti_init(void)
{
	RCC->APB2ENR |= RCC_APB2ENR_SYSCFGEN;
	(void)RCC->APB2ENR;

	SYSCFG->EXTICR[0] &= ~(0xFu << 0);          /* line 0 listens to port A */
	EXTI->FTSR |= (1u << 0);                    /* falling edge trigger */
	EXTI->RTSR &= ~(1u << 0);
	EXTI->IMR  |= (1u << 0);                    /* unmask line 0 */

	NVIC_SetPriority(EXTI0_IRQn, 5);
	NVIC_EnableIRQ(EXTI0_IRQn);
}

void EXTI0_IRQHandler(void)
{
	if (EXTI->PR & (1u << 0)) {
		EXTI->PR = (1u << 0);                   /* clear pending: write 1 */
		pressed_count++;
	}
}

Four details recur in every pin interrupt. The handler must clear the pending bit, here by writing 1 to EXTI_PR, or it re-enters forever. The handler must be short and only set a flag or count, leaving the work to the main loop. Variables shared with the main loop must be volatile. And the vector table must contain the handler's address, which the weak-alias scheme of the startup file does when the function name matches the table's name exactly.

Level-triggered interrupts exist on some chips, such as the RP2040, but a button wants an edge, since a level interrupt fires continuously while the pin stays low.

Contact bounce

A mechanical switch does not close cleanly. For a few milliseconds the contacts make and break, and the pin sees a burst of edges. An interrupt on each edge counts one press as several. The fix is in time, not in count: accept a change only after the signal has been stable, which is debouncing. The simplest robust form samples the pin on a regular tick and uses a shift register of the last eight samples:

c
struct button { uint8_t history; int pressed; };

int button_update(struct button *b, int raw_pressed)
{
	b->history = (uint8_t)((b->history << 1) | (raw_pressed ? 1u : 0u));

	if (!b->pressed && b->history == 0xFFu) { b->pressed = 1; return 1; }
	if (b->pressed && b->history == 0x00u)  { b->pressed = 0; return -1; }
	return 0;
}

The function returns 1 on a debounced press, -1 on a release and 0 otherwise, and it never blocks. Called every 2 ms, it needs 16 ms of stability. The dedicated debouncing post in this cluster covers counter and lockout variants, and how to combine an interrupt with debouncing so the CPU stays asleep until a press begins.

Alternate functions: the pin becomes a peripheral

Most pins can belong to a peripheral instead of to the GPIO logic. The pin's multiplexer chooses among the GPIO and up to sixteen alternate functions, selected by AFRL and AFRH and enabled by setting the pin's mode to alternate function. To connect USART2's TX and RX to PA2 and PA3, whose alternate function number 7 is documented in the datasheet's mapping table:

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

	GPIOA->AFR[0] = (GPIOA->AFR[0] & ~((0xFu << 8) | (0xFu << 12)))
	              | (7u << 8) | (7u << 12);
	GPIOA->MODER  = (GPIOA->MODER & ~((3u << 4) | (3u << 6)))
	              | (2u << 4) | (2u << 6);
}

Both settings are needed: the right alternate function number and the alternate-function mode. A correct number with the pin left in input mode does nothing, and a correct mode with the wrong number connects the pin to some other peripheral signal. The datasheet table, not memory, is the source for the number, since the same signal has different numbers on different parts. The electrical settings of the pin still follow the peripheral: TX is a push-pull output at medium speed, RX an input with a pull-up, and an I2C pin must be open-drain with an external resistor.

A small project that uses all of it

The pieces combine in a short program. Four LEDs on PD12 to PD15 run a chaser pattern at a speed the user changes with a button on PA0, and a debounced press steps through three speeds. It uses clock gates, output configuration, BSRR for the pattern, an input with a pull configuration chosen by the board, a periodic tick and the shift-register debounce, with no blocking delay anywhere:

chaser.cc
#include <stdint.h>
#include "stm32f407xx.h"

struct button { uint8_t history; uint8_t pressed; };

static volatile uint32_t ms;
static struct button user_button;
static const uint32_t step_ms[3] = { 400, 200, 80 };
static uint32_t speed;

void SysTick_Handler(void)
{
	ms++;
}

static void gpio_setup(void)
{
	RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN | RCC_AHB1ENR_GPIODEN;
	(void)RCC->AHB1ENR;

	for (unsigned pin = 12; pin <= 15; pin++) {
		GPIOD->MODER = (GPIOD->MODER & ~(3u << (pin * 2))) | (1u << (pin * 2));
		GPIOD->OSPEEDR &= ~(3u << (pin * 2));
	}
	GPIOA->MODER &= ~(3u << 0);                /* PA0 input; board has an external pull-down */
}

static int button_update(struct button *b, int raw)
{
	b->history = (uint8_t)((b->history << 1) | (raw ? 1u : 0u));
	if (!b->pressed && b->history == 0xFFu) { b->pressed = 1; return 1; }
	if (b->pressed && b->history == 0x00u)  { b->pressed = 0; return 0; }
	return 0;
}

int main(void)
{
	uint32_t next_step = 0, next_sample = 0;
	unsigned lit = 0;

	gpio_setup();
	SysTick->LOAD = 16000u - 1u;                   /* 1 ms at the 16 MHz reset clock */
	SysTick->VAL = 0;
	SysTick->CTRL = SysTick_CTRL_CLKSOURCE_Msk | SysTick_CTRL_TICKINT_Msk | SysTick_CTRL_ENABLE_Msk;

	for (;;) {
		uint32_t now = ms;

		if ((int32_t)(now - next_sample) >= 0) {
			next_sample = now + 2;
			if (button_update(&user_button, GPIOA->IDR & 1u))
				speed = (speed + 1u) % 3u;
		}

		if ((int32_t)(now - next_step) >= 0) {
			next_step = now + step_ms[speed];
			GPIOD->BSRR = (0xFu << (12 + 16)) | (1u << (12 + lit));   /* all off, one on */
			lit = (lit + 1u) % 4u;
		}
	}
}

Three points are worth reading closely. The LEDs change with one BSRR store that clears all four bits and sets one, so there is never a moment with two lit or none lit. The two schedules, the button sample every 2 ms and the pattern step every 80 to 400 ms, are independent deadlines compared against the same tick with (int32_t)(now - next) >= 0, which is correct across the wrap of the 32-bit counter. And nothing waits: a loop iteration takes microseconds, so the button is sampled on time even at the fastest chase. The same structure scales to many inputs and outputs, and replaces the blocking delay that makes a first program unable to do two things at once.

How fast can a pin toggle

A frequent question is what the limit on a pin's switching speed is, and the answer has several parts, each from a different source.

The software. A loop that writes BSRR twice per cycle on a Cortex-M4 at 168 MHz executes a handful of instructions per toggle, and the bus accesses to the peripheral take a few core cycles each, because the GPIO sits behind the AHB bus matrix and the bridge. The achieved frequency is therefore a fraction of the core clock, and you find it by measuring on a scope or with the cycle counter, not by multiplying instructions. A quick measurement uses the DWT cycle counter:

c
#include "stm32f407xx.h"

uint32_t toggle_cycles(void)
{
	CoreDebug->DEMCR |= CoreDebug_DEMCR_TRCENA_Msk;
	DWT->CYCCNT = 0;
	DWT->CTRL |= DWT_CTRL_CYCCNTENA_Msk;

	uint32_t t0 = DWT->CYCCNT;
	for (int i = 0; i < 100; i++) {
		GPIOD->BSRR = (1u << 12);
		GPIOD->BSRR = (1u << (12 + 16));
	}
	return (DWT->CYCCNT - t0) / 200u;          /* cycles per write */
}

The function returns the average core cycles per BSRR write, which you then convert with the clock frequency. The figure depends on the clock tree configuration, the bus prescalers and whether the code runs from cache, which is why a number from a forum post does not apply to your board.

The pin's slew rate. The OSPEEDR setting limits how fast the output edge can move, as the datasheet's I/O output characteristics table shows for each setting and load capacitance. A pin set to low speed cannot produce a clean 10 MHz square wave however fast the software writes.

The load. The wire, the pad and the connected input have capacitance, and the driver charges it through a finite resistance. A long wire or a scope probe adds tens of picofarads and rounds the edges.

The hardware alternative. For a clean fast square wave, do not toggle in software. A timer in output-compare toggle mode generates a precise waveform with no CPU involvement, and the pin is set to its alternate function. The software toggle is for signals where jitter of a few cycles does not matter.

Interfacing with other voltages

Logic families operate at 5 V, 3.3 V, 1.8 V and lower, and a board with several of them needs care at each boundary. Two rules and four techniques cover most cases.

The rules: an input must not be driven above its tolerance, and a driven level must still meet the receiver's VIH and VIL. A 3.3 V output reads as high on most 5 V TTL inputs (VIH 2.0 V) but not on 5 V CMOS inputs (VIH about 3.5 V).

DirectionTechniqueNotes
5 V output to a 3.3 V inputResistor dividerA 2 kilohm and 3 kilohm pair gives 3.0 V from 5 V; fine for slow signals, adds delay with input capacitance
5 V output to a 5 V tolerant 3.3 V pinDirect, if the datasheet allowsCheck the FT marking and the maximum voltage
3.3 V output to a 5 V input that needs high VIHLevel shifter ICA transistor-based or dedicated translator; bidirectional types handle I2C
Bidirectional open-drain (I2C)MOSFET shifter with a pull-up on each sideThe classic single N-channel MOSFET circuit
3.3 V open-drain to a 5 V inputPull-up to 5 VThe pin must be 5 V tolerant; the chip releases the line and the resistor does the rest
Many signals between voltage domainsTranslator IC with direction pinBuses such as SPI or parallel

For slow signals, a series resistor of a few kilohms limits the current through the input protection diodes if a stray higher voltage appears, which is a cheap safeguard on a signal that leaves the board.

Protecting pins from the outside world

A pin that connects to a connector, a cable or a person's finger meets electrostatic discharge, miswiring and noise. The first line of protection is already on the chip, the diodes to the rails and a limited ESD structure, and it is rated for assembly handling, not for the field.

For pins that leave the enclosure, add three things in this order from the pin outward: a series resistor (100 ohm to a few kilohm) that limits fault current into the clamp diodes, a small capacitor to ground (a few tens of picofarads to a nanofarad, depending on the signal speed) that slows fast spikes, and a transient voltage suppressor diode at the connector for serious ESD. Together they form a low-pass filter and a clamp, and all are chosen from the signal's bandwidth: the resistor and capacitor together must pass your signal and attenuate spikes.

Also think about power sequencing. A pin that is driven by another board while this board is unpowered can push current through its clamp diode into the supply rail and partly power the chip through the pin, which causes strange half-alive behaviour. Series resistors and, for hot-plugged signals, buffers with power-off protection prevent it.

Making GPIO code testable

Logic that depends on registers cannot run on a laptop, and logic that does not depend on them can. The debounce function above takes the raw sample as an argument and returns an event; it has no knowledge of GPIO at all, so a host test can feed it a recorded bounce trace and check the output. Keep the hardware access in a few one-line functions and the decisions in plain functions:

c
/* hardware layer: one line each */
static inline int  btn_raw(void)      { return (GPIOA->IDR & 1u) != 0; }
static inline void led_write(int on)  { GPIOD->BSRR = on ? (1u << 12) : (1u << 28); }

/* logic layer: no registers, testable on a host */
int  button_update(struct button *b, int raw);
unsigned next_pattern(unsigned lit);

A host-side test links the logic layer and substitutes values:

c
#include <assert.h>

int main(void)
{
	struct button b = {0};
	int events = 0;
	int trace[] = {0,0,1,0,1,1,0,1,1,1,1,1,1,1,1};

	for (unsigned i = 0; i < sizeof trace / sizeof trace[0]; i++)
		events += button_update(&b, trace[i]);

	assert(events == 1);          /* one press for the whole bounce */
	return 0;
}

The test passes when the bounce in the trace produces exactly one press event, and it runs in milliseconds on any machine with no board attached. The same split helps keypad scanning, pattern generators and state machines.

Common GPIO designs and the mistakes they invite

A few patterns recur in real products, each with a typical error.

DesignTypical errorRemedy
LED indicatorNo resistor, or one sized for a different supplyCompute R = (VDD - V_F) / I and check the pin's current limit
Button with interruptCounting every edge, no debounceInterrupt starts a debounce timer; the timer confirms
Relay or motor driverDriving the coil from the pin, no flyback diodeTransistor, flyback diode, gate pull-down
I2C or 1-Wire linePush-pull mode on a shared lineOpen-drain with an external pull-up
Chip select lineFloating during reset, so the peripheral hears noisePull-up on the select, set the level before enabling the output
Reset or enable line to another chipPin floats at power-up and the chip starts in a bad stateExternal resistor to the safe level
Wake-up inputPull configured for run mode but lost in sleepCheck the sleep-mode behaviour in the reference manual
Parallel busChanging bits with several writesOne BSRR write per port

The chip-select row is the one most often missed. A pin is an input until software configures it, so at power-up the select line to an SPI flash or sensor floats, and the peripheral may see a random selection and respond. A pull-up on the select line, matching its idle level, keeps the device deselected until the firmware takes over, and the firmware writes the output level before switching the pin to output mode, so there is no glitch at the handover.

Moving pins without the CPU

Software that toggles pins burns CPU cycles and is at the mercy of interrupt latency. Three hardware features take the CPU out of the loop, and knowing they exist saves a lot of cleverness.

A timer in output-compare mode drives a pin from its alternate function: the pin toggles, sets or clears when the counter matches a compare value, producing a PWM or a precise pulse train with no code running. The pin's job is then entirely in the AFR and MODER settings, and the waveform is configured through the timer's registers.

A DMA channel can write to GPIOx->BSRR or ODR from a table in memory, paced by a timer event. That produces an arbitrary waveform, such as a custom serial protocol or a stepper pattern, at a rate the CPU could not match and with jitter measured in bus cycles. The same mechanism reads IDR into a buffer on each timer tick, which is a crude logic analyser.

An event system such as the nRF52's PPI or DPPI, or the RP2040's PIO state machines, connects a pin edge directly to a task: start a timer, capture a count, trigger an ADC. The RP2040's PIO goes further and runs small programs that shift data in and out of pins at up to the system clock, which is how its USB host, DVI output and WS2812 LED drivers are built in software on one chip.

The rule behind all three is to move the timing-critical part into hardware and leave the policy in software: the hardware makes the edge on time, and the CPU decides which edges to make.

Choosing pins for a new board

Pin assignment is a design decision that costs little at the start and a lot after a board is built. A short procedure avoids most of the pain:

  1. List every peripheral you need and the signals each one uses, such as the USART2 TX and RX, an SPI bus's four lines, the I2C pair and the ADC channels.

  2. Open the datasheet's alternate-function table and mark which pins can carry each signal. Prefer the default pins that the vendor's examples and the board's reference design use, since drivers and libraries assume them.

  3. Reserve the special pins first: the debug pins (SWDIO and SWCLK), the boot configuration pins, the crystal pins, the reset pin and the USB pins. Do not reuse the debug pins for something else; a design that does cannot be reprogrammed in the field without a boot-pin trick.

  4. Check the analogue channels. ADC inputs are on specific pins, and some analogue pins share a function with a noisy digital one. Keep analogue inputs away from fast digital traces on the board too.

  5. Group related signals on one port when you will write them together, such as a parallel bus, so that one BSRR store updates them all.

  6. Leave a few spare pins on the connector for the signals you will want after the first prototype: a UART for debug output, a pin for a scope probe, a spare LED.

  7. Read the errata for the pin functions you chose. Some alternate functions have constraints, such as a pin that cannot be used for two peripherals at once or a pin with a weaker driver.

Choose the pins before routing the board, not after. Peripherals that can be remapped to several pins give the layout engineer freedom, and every choice made late is a choice paid for in a wire or a respin.

Unused pins and power

An unconnected input can oscillate and draw current in the input buffer. Two safe choices for unused pins are an output driven low with nothing connected, or an input with a pull-up or pull-down. On the STM32 the reset state, a floating input, is not ideal, and the reference manual recommends configuring unused pins as analogue input, which disconnects the input buffer entirely and draws the least. In a battery product this matters; across a fleet of devices a few microamps per pin adds up.

During sleep, pins keep their configured state, so an output driving an LED continues to drive it. A design that sleeps must set outputs to their low-power levels before entering the mode and restore them on wake-up.

Locking a configuration

The LCKR register lets software freeze a pin's configuration (mode, type, speed, pull and alternate function) until the next reset. The sequence is a specific write-write-write-read pattern on the lock key bit, designed so that a stray write cannot lock by accident. A safety-critical pin that must not be reconfigured by a wild pointer can be locked after setup. Most projects never use it.

How the same ideas look on other chips

The structure repeats with other names. The table gives the equivalent of each feature:

FeatureSTM32F4AVR (ATmega328P)RP2040 (Pico SDK)ESP32 (ESP-IDF)nRF52
DirectionMODERDDRxgpio_set_dirgpio_set_directionPIN_CNF.DIR
Output levelODR, BSRRPORTx, PINx togglegpio_put, gpio_set_maskgpio_set_levelOUTSET, OUTCLR
ReadIDRPINxgpio_getgpio_get_levelIN
Pull-upPUPDRPORTx on an inputgpio_pull_upgpio_configPIN_CNF.PULL
Open-drainOTYPERSwitch between input and outputNo direct mode: use pin directionGPIO_MODE_OUTPUT_ODPIN_CNF.DRIVE
Alternate functionAFRL, AFRHFixed per pingpio_set_functionIO MUX and GPIO matrixPSEL registers on the peripheral
InterruptEXTIPin change and INT0/1gpio_set_irq_enabled_with_callbackgpio_isr_handler_addGPIOTE

Two differences are worth knowing. On the AVR, a single write to PINx toggles a pin, a feature the others implement with a separate toggle or XOR register. On the nRF52, a peripheral's pins are chosen by writing pin numbers into the peripheral's own PSEL registers instead of through an alternate-function multiplexer on the pin, which makes any pin available to most peripherals. On the ESP32, a GPIO matrix routes most peripheral signals to any pin, with some pins reserved for flash, boot configuration and input only.

The HAL, briefly

ST's HAL wraps all of the above in a structure and a function. The equivalent of led_init and led_on:

c
GPIO_InitTypeDef gi = {0};

__HAL_RCC_GPIOD_CLK_ENABLE();
gi.Pin   = GPIO_PIN_12;
gi.Mode  = GPIO_MODE_OUTPUT_PP;
gi.Pull  = GPIO_NOPULL;
gi.Speed = GPIO_SPEED_FREQ_LOW;
HAL_GPIO_Init(GPIOD, &gi);

HAL_GPIO_WritePin(GPIOD, GPIO_PIN_12, GPIO_PIN_SET);

HAL_GPIO_Init computes the same register masks as the code above, one pin at a time, and HAL_GPIO_WritePin writes BSRR. Using the HAL is reasonable and faster to write. Knowing the registers lets you read what it does, debug it in the register view of a debugger, and write the two-line version in a hot path.

A debugging checklist

When a pin does not behave, walk this list in order. Most problems fall at the first three items.

CheckHow
Is the port clock enabled?Read RCC->AHB1ENR; the bit for the port must be 1
Is the mode right?Read MODER; compare the two bits for your pin
Is the polarity what you think?Look at the schematic for pull direction and active level
Is another driver using the pin?The last configuration wins; check initialisation order and the alternate-function setting
Is the load too big?Measure the pin voltage with the load connected; a droop means too much current
Is the pin shared with a debug function?PA13, PA14 and others reset to the debugger; reassigning them can lock you out
Is the pin 5 V tolerant, and is the external signal above VDD?Datasheet pin table, "FT" markings
Is the edge too slow or ringing?Scope the signal; adjust OSPEEDR or add a series resistor

The debugger's peripheral view shows IDR as the voltage the chip actually sees, which tells you whether the problem is outside the chip (the pin does not reach the level you wrote) or inside (the register holds something else).

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.