Foundations · Lesson 4 of 11 · about 15 min

GPIO: pins in and out

Light an LED, read a button

GPIO means general-purpose input/output. A pin set as output puts 3.3 V or 0 V on the wire. A pin set as input reads the voltage that comes from outside.

The BoardPilot Learn screen: a lesson with its 3D board preview
Try it live

The real app, running in your browser: this lesson with its 3D preview on a simulated ESP32 DevKit (30 pins). No install, nothing to plug in.

With a pull-up resistor the pin reads 1 when nobody touches the button. Pressing it connects the pin to ground, so pressed reads 0. It feels backwards at first, but it is the standard way to wire a button.

Three steps for any pin

  1. Turn on the clock of the port. Peripherals start switched off to save power; forgetting this is the most common beginner bug.
  2. Set the pin mode: input, output, alternate function (UART, I2C and others) or analog.
  3. Write the output register, or read the input register.
// NUCLEO-F401RE: green LED on PA5, blue button on PC13
RCC->AHB1ENR |= (1 << 0) | (1 << 2);   // 1. clock on for ports A and C
GPIOA->MODER &= ~(3 << (5 * 2));       // 2. PA5: clear its two mode bits
GPIOA->MODER |=  (1 << (5 * 2));       //    01 = output

while (1) {                            // 3. read the button, drive the LED
    if ((GPIOC->IDR & (1 << 13)) == 0) GPIOA->ODR |=  (1 << 5);
    else                               GPIOA->ODR &= ~(1 << 5);
}

In BoardPilot, Test hardware reads and drives real pins, and the 3D board shows every pin you use.

Interview questions

  1. What is a pull-up resistor and why does a button need one?
  2. What is switch bounce and how do you handle it?
  3. Why must you enable a peripheral clock before using it?

No answers here on purpose: try answering out loud first. In the BoardPilot app, the interview coach reads your own answer and tells you what was right, what is missing and what a senior interviewer would ask next (it uses the AI provider you choose in the app). Embedded systems interview questions →

Key terms

In the app, the lessons come alive

The lessons have interactive demos and hands-on labs checked on your board in the app. These pages are the readable version: the demos are described in words, and the labs need the app.

Download BoardPilot Try the lessons in your browser