STM32 GPIO Tutorial: Modes, Functions, and Pin Configuration Explained

I have worked with many microcontrollers, from the early 8051 and PIC devices to the more advanced STM32 family. Among all the peripherals, one that has always been essential is the General-Purpose Input/Output (GPIO).

A GPIO (General-Purpose Input/Output) is a special pin on a microcontroller that you can control through software. Unlike fixed-function pins, which always do one specific job, a GPIO can be set to work in different ways. It can be an input pin (to read signals, like a button press) or an output pin (to send signals, like turning on an LED). This flexibility makes GPIOs the foundation of almost every embedded system.

At first, a GPIO might look simply just a pin that can be either HIGH (1) or LOW (0). But in practice, how you configure it has a big impact. GPIO settings can affect power usage, signal stability, electromagnetic noise (EMI), and the overall reliability of your system.

STMicroelectronics has refined the GPIO architecture in its STM32 family, and the STM32H5 series brings new improvements. Yet, many of the classic pitfalls—such as leakage currents, timing mismatches, or improper pull configurations—still apply if not handled carefully.

In this STM32 GPIO tutorial, we will take a comprehensive look at STM32H5 GPIOs, exploring their modes, registers, electrical behaviors, and practical issues you may encounter in real-world designs.

 

What is GPIO in STM32 Microcontrollers?

In STM32 microcontrollers, General-Purpose Input/Output (GPIO) pins are among the most frequently used peripherals. They provide a flexible interface between the microcontroller core and the external world, allowing pins to function as digital inputs, digital outputs, analog inputs, or alternate peripheral signals.

STM32 devices organize GPIO pins into ports (typically named GPIOA, GPIOB, and so on), with each port supporting up to 16 pins numbered from 0 to 15. Before configuring or using any GPIO pin, it is essential to understand the key parameters that define its behavior:

  • Pin Modes: Input, Output, Alternate Function, or Analog
  • Output Types: Push-Pull or Open-Drain
  • Pull Resistors: Pull-Up, Pull-Down, or No-Pull
  • Speed Settings: Low, Medium, High, or Very High speed

We will see all this behavior in the later section of this STM32 tutorial.

 

STM32 GPIO Pin Structure:

The STM32 GPIO pin structure defines how a physical pin interacts with internal peripherals and external signals. Understanding this architecture helps firmware engineers configure pins correctly for input, output, analog, or alternate functions. Internally, each GPIO pin is much more than a simple wire. It is a complex circuit containing protection diodes, configurable resistors, a Schmitt trigger, and dual driver transistors.

GPIO PIN Structure

 

I/O Protection Diodes in GPIO Pins:

Every GPIO pin in a microcontroller (such as STM32) includes built-in I/O protection diodes connected to VDD and VSS (ground). Before an external signal reaches the internal GPIO logic, it passes through these diodes.

If the input voltage becomes higher than VDD, the upper diode conducts and clamps the voltage (positive injection). If the voltage drops below ground (VSS), the lower diode conducts (negative injection). This keeps the GPIO voltage within safe limits and prevents damage from electrostatic discharge (ESD) and small voltage spikes.

Simple Example:

Suppose an STM32 GPIO pin is powered at 3.3 V:

  • If an external signal rises to 3.6 V, the protection diode redirects the excess voltage toward VDD.
  • If the signal drops to –0.3 V, the lower diode conducts toward ground.

Because of this clamping action, the internal GPIO circuitry is protected from abnormal voltage levels.

Note: These diodes are designed for protection only, not for regular voltage level shifting. Excessive injection current beyond datasheet limits can still damage the microcontroller.

 

Input Driver (Schmitt Trigger):

When a GPIO pin is configured as an input, the incoming signal is first processed by an input driver with a Schmitt Trigger before reaching the CPU.

A Schmitt Trigger introduces hysteresis, meaning it uses two different voltage thresholds to detect logic levels. This prevents small voltage fluctuations, noise, or slow-rising signals from causing multiple unwanted transitions. As a result, the microcontroller detects a clean and stable Logic 0 or Logic 1. The final digital value is then captured in the Input Data Register (IDR).

Simple Example:

Consider an STM32 GPIO input operating at 3.3 V:

  • The signal must rise above a higher threshold to be read as Logic 1.
  • It must fall below a lower threshold to be read as Logic 0.
  • The gap between these thresholds is called hysteresis, which prevents noise from causing false transitions.
Note: When the pin is configured in Analog mode, the Schmitt Trigger and digital input path are physically disconnected. This reduces power consumption and improves analog measurement accuracy.

 

Output Driver (P-MOS & N-MOS)

When a GPIO pin is configured as an output, it is driven by an internal output driver made up of two transistors:

  • a P-MOS transistor connected to VDD, and
  • an N-MOS transistor connected to VSS (ground).

By controlling these transistors, the microcontroller can drive the pin in two commonly used output modes.

Push-Pull Mode:

In push-pull mode, both transistors are active:

  • The P-MOS turns ON to drive the pin HIGH (logic 1).
  • The N-MOS turns ON to drive the pin LOW (logic 0).

This mode provides fast switching and strong drive capability, making it ideal for LED control, chip select signals, and high-speed digital outputs.

Open-Drain Mode:

In open-drain mode, only the N-MOS transistor is used:

  • The pin can actively pull the line LOW.
  • A pull-up resistor (internal or external) is required to bring the line HIGH.

Because multiple devices can safely share the same line, open-drain outputs are commonly used in communication buses such as I²C and for wired-OR logic.

Simple Example:

  • Driving an LED directly from an STM32 GPIO → Push-Pull mode
  • Connecting multiple devices on an I²C SDA or SCL line → Open-Drain mode with pull-up resistor

 

Alternate Function Multiplexer (AF Mux):

In STM32H5 microcontrollers, GPIO pins do not have fixed functions. Behind the I/O circuitry, a digital multiplexer, known as the Alternate Function Multiplexer (AF Mux), determines how each pin is used.

The AF Mux acts like a railway switch, routing the pin’s signal either to the standard GPIO controller or directly to an internal peripheral such as UART, SPI, I²C, or timers. By changing the alternate function setting in software, a single physical pin can take on multiple roles.

Simple Example

  • Configuring PA9 as a GPIO allows you to control an LED or read a button.
  • Configuring the same PA9 as USART1_TX connects the pin directly to the UART peripheral and turns it into a serial transmit line.
Note: Only one function can be active at a time, and the selected alternate function completely defines how the pin behaves.

 

STM32 GPIO Modes Explained:

STM32 MCU provide multiple GPIO modes that define how a pin behaves electrically and how it interacts with internal peripherals. Understanding STM32 GPIO modes, especially STM32 input output mode selection is critical for writing reliable, low-power, and noise-free firmware.

Each GPIO pin can be configured as Input, Output, Alternate Function, or Analog, depending on the application.

Input Mode:

In Input Mode, the GPIO pin is used to read an external signal. The output driver is disabled, and the pin state is sensed through the input buffer.

1. Floating Input:

  • No internal pull-up or pull-down resistor is enabled.
  • The pin voltage depends entirely on the external circuit.

Use case:
When an external device already drives the signal (e.g., push-pull output from another MCU).

Note: Floating inputs are vulnerable to noise if left unconnected.

2.Pull-Up Input:

  • An internal pull-up resistor connects the pin weakly to VDD.
  • Default state is Logic 1 when the pin is not externally driven.

Use case:
Buttons or switches connected to ground (active-low inputs).

3. Pull-Down Input

An internal pull-down resistor connects the pin weakly to ground.

  • Default state is Logic 0.

Use case:
Inputs that should default to LOW when inactive.

 

Output Mode:

In Output Mode, the GPIO pin actively drives a voltage using internal transistors.

1. Push-Pull Output

  • Both P-MOS and N-MOS transistors are used.
  • Pin can actively drive both HIGH and LOW.

Use case:
LEDs, chip-select lines, clock signals, and high-speed digital outputs.

2. Open-Drain Output:

Only the N-MOS transistor is enabled.

  • Pin can pull LOW but cannot drive HIGH.
  • Requires an external or internal pull-up resistor.

Use case:
Shared buses like I²C, wired-AND signals, or multi-device interrupt lines.

3. Alternate Function Mode:

In Alternate Function (AF) Mode, a GPIO pin is internally connected to a peripheral instead of standard GPIO logic.

Used by peripherals: UART, SPI, I²C, TIM (PWM, capture/compare)

How it works:

  • STM32 pins are multiplexed (one pin, multiple functions)
  • AF multiplexer routes the selected peripheral signal
  • AF is selected via AFR registers
  • Electrical settings (pull-up/down, speed, output type) are still set in GPIO registers

4. Analog Mode:

In Analog Mode, both the digital input buffer and output driver are disabled.

Used for: ADC, DAC, OPAMP, comparator inputs

Benefits:

  • Eliminates digital switching noise.
  • Lowest power GPIO mode.
  • Prevents leakage from floating digital inputs.

Use cases:

  • Analog peripherals
  • Unused GPIO pins

 

STM32 GPIO Registers:

Each GPIO port is managed by a set of memory-mapped registers. These registers define how the pins behave:

A) Configuration Registers:

  • MODER → Selects pin mode (Input, Output, Alternate Function, Analog).
  • OTYPER → Defines output type (Push-Pull or Open-Drain).
  • OSPEEDR → Controls output switching speed (affects EMI and power).
  • PUPDR → Enables/disables internal pull-up or pull-down resistors.
  • AFRL / AFRH → Selects alternate function (USART, SPI, I²C, etc.).
  • SECCFGR → Manages secure/non-secure access (TrustZone-enabled devices).
  • HSLVR → Configures high-speed I/O operation at low voltage (device-dependent)

B) Data Registers:

  • IDR → Input Data Register (reads external pin state).
  • ODR → Output Data Register (sets pin state).

C) Set/Reset Registers:

  • BSRR – atomic set/reset of pins.
  • BRR – reset register for clearing outputs.
💡Tip: Always use BSRR for setting or resetting outputs. Writing to ODR directly can cause glitches if an interrupt or another task modifies the same register simultaneously.

 

D) Control & Protection Registers:

  • LCKR → Lock Register (prevents accidental reconfiguration until reset).

STM32 Electrical behavior & speed:

STM32 GPIO electrical behavior and speed settings control how fast a pin switches and how it interacts with external circuitry. Output speed, drive type, and pull resistors directly affect EMI, power consumption, and signal reliability. Here are a few important GPIO points you should understand before initialization.

1. GPIO Output-Speed Configuration

GPIO speed settings control the rising and falling edges when the pin switches state (from HIGH to LOW or vice versa).

  • Low Speed → Best for very slow toggling (e.g., an LED blinking at 1 Hz).
  • Medium Speed → Balanced for general-purpose signals.
  • High / Very High Speed → Required for fast peripherals (e.g., SPI running at 45 MHz).

 

⚠️ Note: Increasing GPIO speed also increases power consumption and EMI noise. Always match the GPIO speed to the actual peripheral requirement.

 

 

👉 Certification Testing Tip: Never set all pins to Very High speed by default. In our products, we have seen designs fail EMI compliance tests solely due to fast GPIO slew rates. The solution was to implement a generic method to configure GPIO speed. Always use the slowest speed that still meets your timing requirements.

 

 

2. Electrical Characteristics:

STM32 GPIO pins are more than simple digital switches—they come with configurable electrical properties:

  • Push-Pull or Open-Drain outputs.
      • Push-Pull: Actively drives both high and low levels, ideal for general-purpose digital outputs.
      • Open-Drain: Only pulls the line low, requiring an external pull-up resistor. Useful for wired-AND logic or communication protocols like I²C.
  • Pull-Up / Pull-Down resistors for stable input levels.
  • Output speed & slew rate control for reducing EMI.
  • Current sourcing/sinking limits per pin and per port.

3. Integration with External Interrupts (EXTI)

  • GPIO pins can be linked to EXTI lines.
  • This allows events like button presses to trigger interrupts or wake the MCU from low-power modes.

4. Security and Low-Power Features (STM32H5 Specific)

  • TrustZone support ensures some GPIOs can only be controlled by secure firmware.
  • HSLVR enables high-speed operation even at reduced supply voltages.
  • GPIOs can be configured as wake-up sources in low-power modes.

 

Note: Each I/O port bit is freely programmable, but the registers must be accessed as 32-bit words, half-words, or bytes.

 

GPIO Initialization:

Before using GPIO pins, you need to enable the clock for the corresponding GPIO port and configure the pin’s properties.

1. Input Configuration:

When configured as input, STM32H5 GPIOs support:

  • Floating Input – High impedance, but highly sensitive to noise.
  • Pull-Up / Pull-Down – Controlled via PUPDR register. Internal resistors are weak; use external resistors for critical signals.

Issue:

Internal pulls change with voltage and temperature. A pin that looks stable HIGH under normal conditions may drop LOW at −40 °C. So never rely only on internal pulls—always use external resistors for critical signals.

 

2. Output Configuration:

When you set a GPIO pin as an output, you need to decide two things:

  • Output Type – how the pin drives signals (Push-Pull or Open-Drain).
  • Drive Strength – how much current the pin can safely source (drive high) or sink (drive low).

Output mode requires setting the OTYPER register:

  • Push-Pull – Drives strong high and low states. Best for LEDs, digital logic, and low-impedance loads.
  • Open-Drain – Pulls only low, requires external pull-up for high. Essential for I²C, multi-master buses, or wired-OR logic.

Current Sinking / Sourcing

  • Sink Current (driving low): up to 8–20 mA depending on the pin and package.
  • Source Current (driving high): slightly weaker than sinking in most STM32 devices.
  • Always consult the I/O Characteristics section of the datasheet; exceeding ratings leads to long-term degradation, not just immediate failure.

 

3. Alternate Functions

GPIO pins on the STM32H5 can take on different roles through the Alternate Function Registers (AFR). This mapping connects internal peripherals — such as UART, SPI, I²C, timers, and CAN — to the physical pin.

Common Pitfalls:

  • Wrong AF index: Choosing the incorrect alternate function silently breaks the connection; the peripheral will not work.
  • Package differences: Not every alternate function is available on every package. Always cross-check the datasheet pinout.
  • Pin conflicts: More than one peripheral may need the same pin. These conflicts must be resolved during PCB design, not after the board is made.

 

✅ Tips When Working on STM32 GPIO:

Here are a few tips that can save you a lot of time when working with STM32xxx GPIO. However, I strongly recommend checking your MCU’s datasheet before applying any of these tips.

1. Always Configure All Pins

  • On some STM32 families (e.g., STM32F1/F4), after reset pins default to input-floating.
  • On newer families like STM32H5, most pins default to Analog mode, which helps reduce leakage current.

Problem: Floating inputs (if left unconfigured) can pick up noise and increase current consumption, especially in low-power modes.

Best Practice: Regardless of defaults, always explicitly configure all unused pins to Analog mode. This disables the input buffer and pull resistors, minimizing power and avoiding undefined states.

2. Use External Pull Resistors for Critical Inputs

  • Internal pull-ups/downs are weak (≈30–50 kΩ) and vary with temperature and voltage.
  • For safety-critical signals (reset, enable, interrupts), always use external resistors.

3. Control Slew Rate for EMI Compliance

  • Output speed (OSPEEDR) controls edge rate, not toggle frequency.
  • Use the lowest speed that meets your timing requirements.
  • Avoid setting all pins to Very High speed — this is a common cause of EMI test failures.

4. Protect Debug Pins

  • Pins PA13/PA14 (SWDIO/SWCLK) are vital for debugging.
  • Reconfiguring them as GPIO too early will lock you out of the chip.
  • Leave them as default until production firmware is finalized.

5. Use BSRR for Atomic Pin Updates

  • Writing to ODR can cause race conditions if interrupts modify the same register.
  • The BSRR register allows atomic set/reset operations per pin — safer and faster.

6. Debounce Inputs Properly

  • EXTI interrupts can trigger multiple times due to mechanical bounce or noise.
  • Use hardware RC filters for push buttons or software debounce logic.

7. Check Current Drive Capability

  • Each GPIO can sink/source up to ~8–20 mA (varies by package).
  • Avoid driving relays, high-power LEDs, or long traces directly.
  • Use external drivers or buffers when higher current is needed.

8. Handle Reset State Hazards

  • Default behavior: After reset, some STM32 GPIOs are configured as high-impedance inputs.
  • Risk: External hardware like motors, MOSFETs, relays, or level-sensitive ICs may float and activate unintentionally.
Best practice:
  • Use external pull-up or pull-down resistors to force a known logic state.
  • Add fail-safe circuits (e.g., series resistors, gate protection, or logic buffers) where accidental activation could cause damage.
  • Review datasheet “reset state” section to confirm the exact pin default for your STM32 family.

9. Review Electrical Domains Carefully

STM32H5 supports multiple I/O voltage domains.

  • Ensure connected peripherals use the same logic level.
  • Driving beyond tolerance (e.g., 5 V input on a 3.3 V pin) can permanently damage the MCU.

10. Always Read the Errata

  • Many GPIO quirks are already documented by ST (e.g., EXTI glitches, leakage in STOP mode).
  • Errata sheets are as important as datasheets.
  • Make it a habit: check errata before every tape-out or certification run.

 

Advanced GPIO Testing:

Advanced GPIO testing goes far beyond just toggling an LED. It is about validating signal integrity, timing behavior, EMC performance, and robustness under real-world conditions.

Over the years, I have seen projects fail not because of complex logic, but due to overlooked GPIO-related issues. Problems often show up at the EMC lab, during cellular interoperability testing, or—worse—later in the field, where debugging is far more costly.

That is why it is critical to have a structured approach to GPIO testing and validation before certification.

In this series, I will highlight some of the most important GPIO tests you should always perform and verify. Each topic will be explained in a separate, detailed blog post to make the learning more practical and interesting.

Now times to explore the key considerations for building a robust GPIO design and ensuring thorough testing.

  • EMC Conformance and Radiated Emission.
  • Cellular IOP (Inter-Operability) Testing.
  • Signal Integrity (SI) Testing.
  • Signaling & Logic Level Compatibility.
  • Leakage Current Minimization.
  • Timing and Synchronization.
  • Troubleshooting Workflow.

 

Frequently Asked Questions (FAQ):

  • What are GPIO modes in STM32?
  • How do I configure STM32 GPIO without HAL?
  • What is alternate function in STM32 GPIO?
  • Why GPIO speed matters in STM32?
  • What is the difference between Push-Pull and Open-Drain?
  • Why should I use BSRR instead of ODR?
  • What happens if I don’t enable the GPIO Clock?
  • How much current can an STM32 GPIO pin sink or source?

 

Recommended Articles for you: