Try Embedded

GPIO

Pin modes, push-pull versus open-drain, pulls, edge interrupts and debouncing.

The simplest peripheral, with the most details

A GPIO (general-purpose input/output) pin can be read as a digital input or driven as a digital output. Almost every product uses dozens of them: LEDs, buttons, chip selects, enable lines, reset lines, interrupt lines from other chips. Most GPIO bugs are electrical, not software, so the details matter.

Configuration registers

Each pin typically has these settings (names from STM32, but every vendor has the equivalent):

SettingOptionsRegister (STM32)
ModeInput, output, alternate function (owned by a peripheral), analogMODER (2 bits per pin)
Output typePush-pull, open-drainOTYPER
Speed / slew rateLow to very highOSPEEDR
PullNone, pull-up, pull-downPUPDR
Alternate functionWhich peripheral (UART, SPI...) drives the pinAFR[0], AFR[1]
DataInput state / output stateIDR / ODR
Atomic set/resetSet or clear individual bitsBSRR

Push-pull and open-drain

Push-pull: the pin actively drives both high (to VDD) and low (to ground). The normal choice for LEDs, chip selects and logic signals.

Open-drain: the pin can only pull low; when "high" it lets go, and a pull-up resistor pulls the line up. Used when:

  • several devices share one line (I2C, interrupt lines wired-OR together): any device can pull it low, none can fight another by driving high
  • the line must be pulled up to a different voltage than the MCU's supply (level shifting), within the pin's tolerance

The pull-up value is a trade-off: small resistors give fast rising edges but waste current while the line is low (3.3 V / 1 kΩ = 3.3 mA); large ones save current but make slow edges.

Inputs, pull-ups and floating pins

An input that is not connected to anything floats: it picks up noise and reads random values, and an input hovering mid-rail also draws extra current in the input buffer. Every input must be driven or pulled:

  • a button between the pin and ground, with the internal pull-up enabled, reads 1 when released and 0 when pressed ("active low")
  • unused pins should be configured as analog (lowest power on most parts) or output low, never left as floating inputs

Internal pulls are weak (typically 30 to 50 kΩ). That is fine for a button, but too weak for a fast bus or a long cable.

Writing outputs without races

GPIOA->ODR |= (1u << 5) is a read-modify-write. If an interrupt changes another pin of port A between the read and the write, its change is lost. The set/reset register avoids this: writing a 1 to a bit in the low half sets that pin, writing a 1 in the high half clears it, and zeros do nothing, so no read is needed.

#include <stdio.h>
#include <stdint.h>

typedef struct {
  volatile uint32_t MODER, OTYPER, OSPEEDR, PUPDR, IDR, ODR, BSRR;
} gpio_t;

static gpio_t porta;                 /* stands in for GPIOA at 0x40020000 */

/* Model of the hardware's BSRR behaviour: a write updates ODR, then reads back as 0. */
static void bsrr_write(gpio_t *g, uint32_t v) {
  g->ODR |= (v & 0xFFFFu);
  g->ODR &= ~(v >> 16);
}

int main(void) {
  /* PA5 output (MODER = 01), PA0 input with pull-up (PUPDR = 01) */
  porta.MODER = (porta.MODER & ~(3u << 10)) | (1u << 10);
  porta.PUPDR = (porta.PUPDR & ~(3u << 0)) | (1u << 0);

  bsrr_write(&porta, 1u << 5);            /* set PA5 */
  bsrr_write(&porta, 1u << 3);            /* set PA3: PA5 untouched */
  printf("ODR = 0x%04X\n", porta.ODR);
  bsrr_write(&porta, 1u << (5 + 16));     /* reset PA5 */
  printf("ODR = 0x%04X\n", porta.ODR);
  printf("MODER = 0x%08X, PUPDR = 0x%08X\n", porta.MODER, porta.PUPDR);
  return 0;
}

Edge interrupts

Instead of polling, a pin can raise an interrupt on a rising edge, falling edge or both (EXTI on STM32, GPIOTE on nRF, "pin change" on AVR). Typical uses: a data-ready line from a sensor, a button, a wake-up signal from sleep.

Watch for:

  • Shared vectors. Several pins often share one interrupt (EXTI lines 10 to 15 on STM32); the handler must check which pin's flag is set.
  • One pin number per line. On STM32, PA3 and PB3 share EXTI line 3, so only one of them can be an interrupt source.
  • Missed edges. If two edges arrive before the handler runs, you see one. For counting fast pulses, use a timer's input capture or counter mode instead.

Debouncing

Buttons and other mechanical contacts bounce, producing a burst of edges for every press. Debouncing them in software, by sampling on a timer, is covered in the interrupts and timing lesson.

Pitfall: Driving an output into a pin that is also driven by another device (two push-pull outputs fighting) can damage both. When a line is shared or its owner is uncertain at reset, use open-drain or put a series resistor in.

Electrical limits worth knowing

  • Current per pin is limited (often 8 to 25 mA) and there is a total per port and per package. Drive relays, motors and long LED strings through a transistor.
  • 5 V tolerance varies per pin; check the datasheet's "FT" marking before connecting 5 V logic.
  • Slew rate: use the lowest speed setting that works. Fast edges cause ringing and radiated noise.
  • State at reset: pins are usually inputs (often floating) until the firmware configures them. Add external pull resistors on lines that must be in a defined state during boot, such as a motor driver's enable.

Interview question: When would you configure a GPIO as open-drain?

Answer: When several devices share a line and any of them must be able to pull it low without fighting another driving it high, as with I2C SDA and SCL, wired-OR interrupt or reset lines. Also when the line is pulled up to a different voltage from the MCU's supply (simple level shifting, within the pin's tolerance). It needs a pull-up, and the resistor value trades rise time against current while the line is low.

Build it: the greenhouse pump and its water-now button

This is step 1 of the module project, a smart greenhouse controller. You write the code against the chip's real register layout, and the lab plays the circuit around it: the relay module, the pump and a button.

Lab: Switch the pump without a start-up twitch

The greenhouse's water pump runs from a relay module on PA8. Like most cheap relay boards, its input is active low: PA8 low switches the relay on and the pump runs; PA8 high (or left floating, because the module has its own pull-up) keeps it off. A water-now button on PA0 connects the pin to ground when it is pressed. There is no resistor on the board for it.

The last firmware had a field bug: every time the controller powered up, the pump ran for a few milliseconds and spat water over the electronics. Write the driver so that cannot happen:

  • pump_init() makes PA8 a push-pull output with the pump off from the very first instant, and makes PA0 an input with the internal pull-up. Change only those pins' bits: PA13 and PA14 carry the debugger.
  • pump_set(on) switches the pump with one write to BSRR, so an interrupt that changes another pin of the port cannot be undone.
  • button_pressed() returns true while the button is held.

Every change of an output pin appears in the output, such as gpioa: pin 8 low. That line is the pump starting.

Going deeper

Interview question: How would you drive a greenhouse pump through a relay without it twitching at power-up?

Answer: Know the relay module's trigger level: many are active low, so the pin must be held at the inactive level from reset, with a pull resistor on the board and the output level written before the pin becomes an output. Add a flyback diode across the coil, or use a module that has one. Test the power-up behaviour with a scope on the relay input.

Interview question: What is the risk of reconfiguring a pin's mode while it is driving a load?

Answer: Changing MODER in two steps (clear then set), or switching from input to output before the output data register holds the right level, can briefly drive the pin to the wrong state, a glitch that can pulse a motor driver's enable or reset an external chip. Set the output data register first, then write the mode field in one write, and add external pull resistors on lines that must stay defined during boot and reconfiguration.

Interview question: How many external interrupt lines does an STM32 have for GPIOs, and what limitation follows?

Answer: Sixteen EXTI lines for GPIOs, one per pin number, each multiplexed between ports. So PA3 and PB3 cannot both generate interrupts, since they share EXTI line 3, and lines 5 to 9 and 10 to 15 share interrupt vectors, so a handler must check the pending register to see which pin fired. Pin assignments for interrupt inputs must be planned with this in mind.

Explain it: In your own words, explain the difference between push-pull and open-drain outputs and when each is used.

Answer: A push-pull output actively drives the line both high, to the supply, and low, to ground, giving fast clean edges; it is the default for LEDs, chip selects and logic signals with a single driver. An open-drain output can only pull the line low; when it is 'high' it simply lets go and a pull-up resistor pulls the line up. That lets several devices share one line without ever fighting, as on I2C or a shared interrupt line, and lets the line be pulled up to a different voltage, at the cost of slower rising edges.