GPIO Programming
Pin configuration, input/output modes, pull-up/down.
GPIO (General Purpose Input Output) is the most fundamental peripheral in any microcontroller. It is the hardware interface between the processor and the physical world, allowing digital signals to be read from sensors, switches, and encoders, or driven to LEDs, relays, and actuators. Mastering GPIO configuration is the first practical skill in embedded systems programming.
Core Concept Explanation
A GPIO port is a group of pins (typically 16 on STM32) controlled by a set of memory-mapped registers. Because the registers are memory-mapped, you configure and control GPIO using standard load and store instructions to specific addresses. The processor does not need a separate instruction to talk to peripherals. This is called the memory-mapped I/O (MMIO) model.
Before any GPIO pin can be used, its clock must be enabled via the RCC (Reset and Clock Control) peripheral. This is a common mistake for beginners. On STM32, for example, you write to RCC_AHB1ENR to enable the GPIOA or GPIOB clock. Without clock enable, writes to GPIO registers have no effect.
The MODER register allocates 2 bits per pin (so 32 bits cover 16 pins). Values are: 00 for input, 01 for general-purpose output, 10 for alternate function (used by UART, SPI, I2C peripherals), and 11 for analog mode (used by ADC/DAC). This is the primary configuration step for any GPIO pin.
Mathematical Expression
To configure pin N of a GPIO port to output mode, the MODER register must have bits [2N+1 : 2N] set to 01. The bit manipulation formula is:
MODER = (MODER and NOT(3 left-shifted by 2N)) or (1 left-shifted by 2N). The first part clears the 2-bit field for pin N, and the second part sets it to 01 (output). For example, to configure pin 5 as output: clear bits [11:10] then set bit 10.
For the BSRR (Bit Set/Reset Register), writing 1 to bit N sets pin N high, and writing 1 to bit (N+16) resets pin N low. This is an atomic operation meaning it cannot be interrupted between set and reset, which is important in interrupt-driven systems. ODR read-modify-write is not atomic and should be avoided in ISRs.
Practical Understanding
Push-pull output mode drives the pin actively to both VCC and GND using two complementary transistors. This is the default mode for most digital outputs such as driving LEDs. Open-drain mode only pulls the pin low using the lower transistor. To drive it high, an external pull-up resistor is needed. Open-drain is used for I2C communication and for wired-AND configurations where multiple devices share one signal line.
Pull-up and pull-down resistors prevent a floating input. When a pin is configured as input with no external connection, it floats between logic levels and reads unpredictably. Enabling the internal pull-up (PUPDR = 01) connects the pin to VCC through a resistor (typically 40 kOhm on STM32), and pull-down (PUPDR = 10) connects it to GND. The appropriate choice depends on the logic convention of the connected sensor or switch.
The output speed register (OSPEEDR) controls the slew rate of the output driver, not the PWM frequency. Higher speed settings increase power consumption and EMI. For most GPIO toggling below 1 MHz, low or medium speed is sufficient. High speed is needed for SPI clock lines or high-frequency PWM outputs.
Given:
STM32F4 microcontroller. Configure GPIOA Pin 5 as push-pull output.
GPIOA base address = 0x40020000
MODER offset = 0x00
OTYPER offset = 0x04
RCC_AHB1ENR address = 0x40023830
Why this formula applies:
MODER uses 2 bits per pin. Pin 5 = bits [11:10]. Output mode = 01.
Formula:
MODER = (MODER AND ~(0x3 << (5*2))) OR (0x1 << (5*2))
Substitution:
Clear bits [11:10]: MODER AND ~(0x3 << 10) = MODER AND ~(0xC00)
Set bit 10: OR (0x1 << 10) = OR 0x400
Calculation:
Step 1: Enable GPIOA clock: RCC_AHB1ENR |= (1 << 0)
Step 2: GPIOA_MODER &= ~(0x3 << 10) // clear bits 11:10
Step 3: GPIOA_MODER |= (0x1 << 10) // set to output (01)
Step 4: GPIOA_OTYPER &= ~(1 << 5) // push-pull (bit5 = 0)
Final Answer:
GPIOA Pin 5 is now configured as push-pull output. Write 1 to BSRR bit 5 to set high.Exam Tip: A very common trap in university exams is forgetting clock enable (RCC). Also note that BSRR is write-only and provides atomic bit manipulation. ODR is read-write but non-atomic. For thread-safe or ISR-safe GPIO toggling, always use BSRR, not ODR.
GPIO Modes in Summary
- Input mode (MODER=00) connects the pin to the input data register (IDR). The pin state can be read as 0 or 1. Configure PUPDR to avoid floating inputs when no external bias is present.
- Output mode (MODER=01) drives the pin from the output data register (ODR) or via BSRR. Use push-pull (OTYPER=0) for standard digital outputs. Use open-drain (OTYPER=1) for I2C or wired-AND bus lines.
- Alternate function mode (MODER=10) connects the pin to an internal peripheral such as UART TX/RX, SPI MOSI/MISO/SCK, or I2C SDA/SCL. The AFR register selects which alternate function (AF0 to AF15).
- Analog mode (MODER=11) disables the digital input/output buffers and connects the pin directly to the ADC or DAC. This reduces power and avoids spurious digital transitions on analog signals.
- BSRR is the preferred register for atomic output control. Bits [15:0] set individual pins, bits [31:16] clear individual pins. No read-modify-write cycle is needed, making it safe in interrupt contexts.
Quick Revision
- Always enable GPIO clock via RCC before accessing GPIO registers. Writes without clock enable are silently ignored.
- MODER: 00=input, 01=output, 10=alternate function, 11=analog. 2 bits per pin, 32 bits for 16 pins.
- OTYPER: 0=push-pull (default), 1=open-drain. Open-drain requires external pull-up resistor to drive high.
- PUPDR: 00=none, 01=pull-up, 10=pull-down. Always set for input pins to avoid floating.
- BSRR bits [15:0] set pins high; bits [31:16] clear pins. Atomic operation, safe in ISRs.
- Trap: ODR read-modify-write is not atomic. If an interrupt fires between read and write, the pin state may be corrupted. Use BSRR instead.
- OSPEEDR controls slew rate only, not frequency. Higher speed increases EMI. Use low/medium for general purpose toggling.
GPIO Programming Practice
Test your knowledge on this topic!
Q1.What hardware capability is missing from a GPIO pin configured in open-drain output mode?
Related Articles
External Interrupts
EXTI line configuration.
6 min read
Interrupt Priority
Preemption priority vs sub-priority.
9 min read
Interrupts
Hardware vs Software, IVT structure, INT n instruction.
6 min read
Embedded Systems Overview
Definition, constraints, design metrics.
9 min read
BIOS Interrupts
INT 10h video services, INT 16h keyboard.
10 min read