Skip to content
Tutorials Center
My learning

Topics

Lesson 16 of 37 ยท Memory, Registers and Peripherals

GPIO in Depth

Understand GPIO pin modes (input, push-pull, open-drain, alternate function), pull-up and pull-down resistors, active-low logic, drive strength and reading buttons correctly.

GPIO (general-purpose input/output) is the simplest peripheral and the one you use most. Each pin can read a voltage as a 0 or a 1, or drive a voltage out. But "just a pin" hides real electronics: a pin can float, be pulled, drive hard or only pull low, and share a wire with other devices. Picking the right mode is the difference between a button that works and one that randomly triggers, and between a bus that works and a short circuit.

This lesson explains the internal structure of a pin, each mode and when to use it, pull resistors, active-low signals, current limits and how to read inputs safely. A simulated pin model lets you experiment with floating inputs and open-drain buses.

Inside a pin

A GPIO pin connects to the outside through a few building blocks:

flowchart LR
    ODR["Output data<br/>(ODR bit)"] --> DRV["Output driver<br/>push-pull or open-drain"]
    DRV --> PAD(("Pin"))
    PU["Pull-up / pull-down<br/>resistor (~40 kohm)"] --- PAD
    PAD --> SCH["Input buffer<br/>(Schmitt trigger)"]
    SCH --> IDR["Input data<br/>(IDR bit)"]
    AF["Peripheral signal<br/>(UART TX, SPI CLK)"] -.-> DRV
  • The output driver has two transistors: one connecting the pin to VDD (the "high side") and one to ground (the "low side").
  • The pull resistor (optional, software-selectable) weakly ties the pin to VDD or ground.
  • The input buffer is a Schmitt trigger: it has two thresholds, so a slowly changing or noisy input does not make the output chatter.
  • A multiplexer can hand the pin to a peripheral (UART, SPI, timer, ADC) instead of the GPIO logic: this is the alternate function.

The pin modes

Mode Behavior Typical use
Input, floating high impedance, reads whatever is connected external logic that always drives the line
Input with pull-up weak resistor to VDD buttons wired to ground, open-drain buses
Input with pull-down weak resistor to ground buttons wired to VDD
Output push-pull actively drives high (VDD) and low (0 V) LEDs, logic signals, chip selects
Output open-drain actively pulls low; "high" means released I2C, shared interrupt lines, level shifting
Alternate function pin driven by a peripheral UART, SPI, I2C, PWM, USB
Analog digital buffers disconnected ADC input, DAC output, saves power

Floating inputs

An input with nothing driving it floats: its voltage drifts with noise and touch, and the digital reading flips randomly. Never leave a used input unconnected: always give it a defined level with a pull resistor (internal or external). Unused pins are often best configured as analog or as outputs, to avoid wasted current from floating inputs.

Pull-up and pull-down

A button connected between the pin and ground needs a pull-up: unpressed, the resistor holds the pin high; pressed, the button shorts it to ground and the pin reads low. This is the most common wiring because it needs only the internal resistor and no external parts. The logic is active-low: pressed = 0.

Push-pull vs open-drain

A push-pull output can drive both levels, so two push-pull outputs fighting on one wire (one high, one low) create a short circuit. An open-drain output can only pull the line low, or let go. A pull-up resistor creates the high level when nobody pulls low. That makes open-drain safe to share: any device can pull the wire low, and the line is high only when all release. This is a wired-AND and is the basis of I2C. It also allows a 3.3 V device to talk on a 5 V line with a pull-up to 5 V (if the pin is 5 V tolerant).

C Wired-AND: three open-drain devices on one wire

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Reading a button correctly

Typical sequence for a button on pin PC13 wired to ground:

  1. Enable the port clock.
  2. Set the pin as input with pull-up.
  3. Read the input data register; mask the pin; remember that 0 means pressed.
  4. Debounce (see State Machines in C) or use an interrupt with a debounce timer.

The simulation models the electrical truth: a pin has a mode, a pull setting and an external signal. The pin level seen by the CPU depends on all three.

C What does the pin read? Floating, pull-up and a button

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The floating lines print random bits (the exact sequence depends on the C library); that is what a real unconnected input looks like.

Outputs: current, LEDs and loads

A pin cannot supply unlimited current. Typical limits: 8 to 25 mA per pin and a total per port or chip. Consequences:

  • An LED needs a series resistor: R = (VDD - Vf) / I. For a 3.3 V pin, a red LED with Vf = 2.0 V and 5 mA needs (3.3 - 2.0) / 0.005 = 260 ohm; use 330 ohm.
  • You can drive an LED either sourcing (pin high turns it on, LED to ground) or sinking (pin low turns it on, LED to VDD). Sinking is often stronger on older chips and means the LED is active-low.
  • Never connect a motor, relay, speaker or large LED strip directly to a pin. Use a transistor or MOSFET (and a flyback diode for coils), or a driver IC.
  • Slew rate/speed: fast output speed settings give sharper edges but create more electromagnetic noise. Use the slowest speed that works.
C LED resistor and current budget

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Configuring a pin with registers

On STM32 chips, each pin has two bits in MODER (00 input, 01 output, 10 alternate, 11 analog), one bit in OTYPER (push-pull or open-drain), two bits in OSPEEDR and two bits in PUPDR. Setting pin 5 as a push-pull output looks like this (read-only, for a real STM32F4):

C
RCC->AHB1ENR |= RCC_AHB1ENR_GPIOAEN;                 // clock the port
GPIOA->MODER   = (GPIOA->MODER & ~(3u << (2 * 5))) | (1u << (2 * 5));   // output
GPIOA->OTYPER &= ~(1u << 5);                         // push-pull
GPIOA->PUPDR  &= ~(3u << (2 * 5));                   // no pull
GPIOA->BSRR    = (1u << 5);                          // set high, atomically

The two-bits-per-pin pattern uses exactly the field-writing technique from Bit Manipulation for Registers. Other families differ in names (Pico's gpio_set_function, nRF's PIN_CNF[n]) but the model above applies.

Good habits

  1. Configure the pin's output level before switching it to output, so it does not glitch.
  2. Leave unused pins in a defined state (analog or output low).
  3. Add pull resistors externally on critical lines; internal ones are weak and vary (20-50 kohm).
  4. Use series resistors (100 ohm) on fast lines that leave the board, and ESD protection on connectors.
  5. Treat 5 V as dangerous unless the pin is documented as 5 V tolerant.
  6. Document active levels in names: LED_ON_LEVEL, BUTTON_PRESSED_LEVEL.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. A button connects a GPIO pin to ground. Which input mode should you use?

    The pull-up keeps the pin high while released; pressing shorts it low. Without it the pin would float.
  2. 2. Why is open-drain suitable for sharing one wire among many devices?

    Open-drain avoids the short circuit of one device driving high while another drives low.
  3. 3. What value should the resistor be for a 2.0 V LED at 5 mA from a 3.3 V pin?

    R = (3.3 - 2.0) / 0.005 = 260 ohm. Use the next standard value, 270 or 330 ohm.
  4. 4. What is a floating input?

    An undriven, unpulled input picks up noise and its value is undefined.

Summary

  • A GPIO pin has an output driver (push-pull or open-drain), optional pull resistors, a Schmitt-trigger input and a multiplexer for alternate functions.
  • Never leave a used input floating; buttons to ground use pull-ups and are active-low.
  • Open-drain lines are wired-AND and shareable; push-pull outputs must never be connected together.
  • Size LED resistors from (VDD - Vf) / I; never drive motors or relays directly from a pin.
  • Configure pins with the field-writing pattern, set the output level first and keep unused pins in a defined state.

Next: Startup Code, Linker Sections and the Stack