Skip to content

Part 2: Controlling an LED with GPIO

An LED is a useful first output because you can see what the program does. Identify the physical connection and Linux GPIO chip before applying output; successful compilation alone does not check the circuit.

Sample code on GitHub

Sample and README · C++ source · CMake build instructions

The repository's CMake target is gpio_led; its source file is named main.cpp. The direct-build instructions below remain available.

Before you start

Complete C++ Setup. You need a Pi with a 40-pin header, a low-current indicator LED, a 1 kΩ series resistor, breadboard and jumper wires.

The wiring below applies to the standard Pi 4/5 header. The available validation board is a Pi 4B. Pi 5 uses a different controller: identify its chip and line information rather than assuming a chip number. The program requires line offset 24 to be named GPIO24 and refuses a mismatch.

All compilation and inspection commands run on the Pi. You will first run without hardware access; adding --apply is a separate, deliberate step.

1. Understand the three numbering systems

Name This lesson Meaning
Physical header pin 18 Position on the 40-pin connector
GPIO number GPIO24 The signal assigned to that position
Chip line offset 24 on the confirmed header controller Index used by the Linux API

Physical pin 24 is not GPIO24. It is a different signal. Check the official header reference, orient the board correctly and locate pin 1 before counting.

2. Wire with all power disconnected

Shut the Pi down, wait for shutdown, and unplug power before wiring. Remove other connections to GPIO24.

Physical pin 18 (GPIO24) ── 1 kΩ resistor ── LED anode
LED cathode ── Physical pin 6 (GND)

The anode is usually the longer lead on an untrimmed LED; the cathode often has a shorter lead/flat package edge. Use its datasheet if uncertain. The resistor can be on either side of the LED as long as it is in series, not parallel.

For a red LED with an illustrative 2 V forward drop, (3.3 - 2) / 1000 gives about 1.3 mA. Actual current depends on the LED and GPIO voltage. This conservative starting circuit may be dim; do not lower resistance without checking component/current requirements.

GPIO is a signal, not a power supply

Never connect 5 V to GPIO24, short the output to ground, or omit the resistor. Do not substitute a high-power LED, motor or unknown module for the indicator LED.

Check before power: GPIO24 → resistor → LED → ground is one series path; no wire bridges 5 V or adjacent pins. Then reconnect power and log in.

An earlier LED project

The existing demonstration image is not a verification of your wiring or the revised code.

3. Identify the GPIO controller and access

If the inspection commands are absent, install gpiod intentionally with APT; it supplies command-line tools, not a required library for this program.

sudo apt update
sudo apt install gpiod

Skip installation if the tools already exist. Review APT's proposed changes before confirming.

1
2
3
4
5
gpiodetect
gpioinfo --version
gpioinfo
id
ls -l /dev/gpiochip*

Find the chip exposing the header signals and its line named GPIO24. Check its offset and consumer/used status. On the validation Pi, gpiodetect reports gpiochip0 [pinctrl-bcm2711] (58 lines) and offset 24 is named GPIO24. This is a Pi 4 observation, not a universal path.

With libgpiod v2 tools, the targeted inspection command is:

gpioinfo -c gpiochip0 24

Replace the chip with yours. Older libgpiod v1 tools use different options; gpioinfo --help documents the installed CLI. Do not release a line used by another driver/process merely to complete this exercise.

The account usually needs the actual device's group access. Use Users and Permissions rather than chmodding devices or assuming root is mandatory.

4. Save and build the C++ GPIO example

Create a new project directory, then use nano to save the code below as gpio_led.cpp. The downloadable source is the same program.

1
2
3
led_dir=$(mktemp -d "$HOME/pi-led-practice.XXXXXX")
cd "$led_dir"
nano gpio_led.cpp
#include <cerrno>
#include <chrono>
#include <csignal>
#include <cstring>
#include <fcntl.h>
#include <iostream>
#include <linux/gpio.h>
#include <sys/ioctl.h>
#include <thread>
#include <unistd.h>

namespace {
volatile std::sig_atomic_t stopped = 0;
void stop(int) { stopped = 1; }
}

int main(int argc, char* argv[])
{
    constexpr unsigned offset = 24;
    if (argc < 2 || argc > 3 ||
        (argc == 3 && std::strcmp(argv[2], "--apply") != 0)) {
        std::cerr << "Usage: gpio_led /dev/gpiochipN [--apply]\n";
        return 1;
    }
    if (argc == 2) {
        std::cout << "Dry run: GPIO24, physical pin 18, ten 500 ms blinks.\n"
                     "Verify chip and wiring before adding --apply.\n";
        return 0;
    }
    std::signal(SIGINT, stop);
    std::signal(SIGTERM, stop);
    const int chip = open(argv[1], O_RDONLY | O_CLOEXEC);
    if (chip < 0) {
        std::cerr << "Open chip: " << std::strerror(errno) << '\n';
        return 1;
    }
    gpio_v2_line_info info{};
    info.offset = offset;
    if (ioctl(chip, GPIO_V2_GET_LINEINFO_IOCTL, &info) < 0 ||
        std::strcmp(info.name, "GPIO24") != 0) {
        std::cerr << "Cannot confirm GPIO24 at offset 24; no line requested.\n";
        close(chip);
        return 1;
    }
    gpio_v2_line_request request{};
    request.offsets[0] = offset;
    request.num_lines = 1;
    request.config.flags = GPIO_V2_LINE_FLAG_OUTPUT;
    request.config.num_attrs = 1;
    request.config.attrs[0].attr.id = GPIO_V2_LINE_ATTR_ID_OUTPUT_VALUES;
    request.config.attrs[0].attr.values = 0; // Initially low.
    request.config.attrs[0].mask = 1;       // Index 0 in the requested set.
    std::strcpy(request.consumer, "pi-course-led");
    if (ioctl(chip, GPIO_V2_GET_LINE_IOCTL, &request) < 0) {
        std::cerr << "Request GPIO24: " << std::strerror(errno) << '\n';
        close(chip);
        return 1;
    }
    auto set_value = [&](bool high) {
        gpio_v2_line_values values{};
        values.mask = 1;
        values.bits = high ? 1 : 0;
        if (ioctl(request.fd, GPIO_V2_LINE_SET_VALUES_IOCTL, &values) < 0) {
            std::cerr << "Set value: " << std::strerror(errno) << '\n';
            return false;
        }
        return true;
    };
    bool ok = true;
    for (int blink = 0; blink < 10 && !stopped; ++blink) {
        if (!set_value(true)) { ok = false; break; }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
        if (!set_value(false)) { ok = false; break; }
        std::this_thread::sleep_for(std::chrono::milliseconds(500));
    }
    if (!set_value(false)) ok = false;
    close(request.fd);
    close(chip);
    std::cout << "Line released; inspect the LED before disconnecting power.\n";
    return ok ? 0 : 1;
}

Build and run the planning mode:

g++ -std=c++17 -Wall -Wextra -Wpedantic -g -pthread gpio_led.cpp -o gpio_led
./gpio_led /dev/gpiochip0

Use your confirmed chip path. Without --apply the program prints the intended line and ten slow blinks, but does not open a GPIO device.

5. Apply only after the wiring and chip checks

The following requests GPIO24 as an output, initially low, then blinks it ten times at approximately half a second on/off:

./gpio_led /dev/gpiochip0 --apply

Success: the LED alternates visibly and is low before the program releases the line. Use Ctrl+C to stop normally; the signal handler sets a flag, and the main loop performs cleanup. Cleanup may take up to roughly one blink cycle.

The API mask 1 selects index 0 of the requested line set, not “GPIO1”. The kernel owns the line request until its descriptor is closed. These operations occur from a userspace process; it is incorrect to call the entire program kernel-space code.

This is slow visible blinking, not precise PWM. Linux scheduling can delay the sleep. Release does not guarantee the pin remains low indefinitely; reset, another consumer or forced termination can change its state. It is not a safety controller.

Troubleshooting

Symptom Check
Open chip: Permission denied Correct path, device mode and current-session groups
Cannot confirm GPIO24 Wrong chip, unsupported line names or offset; stop and inspect
Line request busy Existing consumer; do not forcibly take it
Program works but LED stays dark Power off and check physical pin, LED polarity and series resistor
LED always on Verify wiring and whether another source powers it
Compiler lacks v2 definitions Current Linux headers; do not silently switch to an old incompatible example

Compilation, planning mode, argument/error paths and chip metadata are verified separately. The revised LED circuit was not connected or physically blink-tested for this revision. Do not treat its dry run as an electrical test.

Practice before the next lesson

Without connecting hardware, predict the nominal duration of ten blinks when both the high and low sleeps are changed from 500 ms to 250 ms. In a practice copy, identify both sleep statements and the dry-run description that would also need updating. Run only planning mode.

Hint and expected result

Ten cycles × (250 ms high + 250 ms low) = 5000 ms. That is a requested schedule, not a measured electrical timing guarantee. Changing only one sleep changes the duty ratio. Keep the dry-run description consistent with the edited code; do not add --apply for this exercise.

Check your understanding and continue

Can you point to GPIO24's physical pin and its Linux chip offset without confusing them? Why must the resistor be in series? What happens when the program releases a request?

Next, learn Button Input.

Donate