Skip to content

Part 3: Controlling GPIO Input with a Tactile Switch

A push button connects or disconnects a circuit; it does not produce a reliable digital value by itself. This lesson uses an input pull-up and accepts a state only after it remains stable for a short interval.

Sample code on GitHub

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

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

Before you start

Complete LED Control, including chip identification and permissions. You need a standard Pi 4/5 40-pin header, an unpowered momentary button, breadboard and wires. Do not use an unknown powered switch module.

Compile and inspect on the Pi. Planning mode does not access GPIO; applying the program configures an input and pull-up. The program requires the confirmed chip's offset 22 to be named GPIO22.

1. Wire and understand the button

With the Pi shut down and all power disconnected:

Physical pin 15 (GPIO22) ── normally open button ── physical pin 6 (GND)

A four-leg tactile switch often has two permanently connected legs on each side. Use a continuity meter with the circuit unpowered to find the two different contact groups that connect only when pressed. Connecting two legs already joined internally makes the input appear permanently pressed.

Do not connect the button to 5 V. Do not configure this grounded button circuit as an output: a high output shorted through the pressed switch can damage GPIO.

The internal pull-up holds the released input high. Pressing connects it to ground:

Button Electrical value Application meaning
Released High, 1 Not pressed
Pressed Low, 0 Pressed

This is called active-low logic. The program interprets that explicitly rather than setting the API's active-low flag. If pull-up configuration is unsupported, stop and diagnose the error; do not run with a floating input.

Earlier tactile switch project

This photo is illustrative and does not identify the correct contact pairs for every switch.

2. Verify the chip and input line

After restoring power, use the chip from the LED lesson. With libgpiod v2 tools:

gpioinfo -c gpiochip0 22

Substitute the actual chip; older CLI versions differ. Confirm the line name, offset and lack of an existing consumer. On the available Pi 4B, offset 22 is named GPIO22. Do not assume the number in gpiochipN is the physical GPIO number.

3. Save and compile the program

Create a new project directory and save gpio_button.cpp using nano, or use the matching source download.

1
2
3
button_dir=$(mktemp -d "$HOME/pi-button-practice.XXXXXX")
cd "$button_dir"
nano gpio_button.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 = 22;
    if (argc < 2 || argc > 3 ||
        (argc == 3 && std::strcmp(argv[2], "--apply") != 0)) {
        std::cerr << "Usage: gpio_button /dev/gpiochipN [--apply]\n";
        return 1;
    }
    if (argc == 2) {
        std::cout << "Dry run: GPIO22, physical pin 15, input with pull-up.\n"
                     "Samples every 5 ms, accepts 25 ms stable changes for 30 s.\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, "GPIO22") != 0) {
        std::cerr << "Cannot confirm GPIO22 at offset 22; 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_INPUT | GPIO_V2_LINE_FLAG_BIAS_PULL_UP;
    std::strcpy(request.consumer, "pi-course-button");
    if (ioctl(chip, GPIO_V2_GET_LINE_IOCTL, &request) < 0) {
        std::cerr << "Request GPIO22: " << std::strerror(errno) << '\n';
        close(chip);
        return 1;
    }
    using Clock = std::chrono::steady_clock;
    bool candidate = true; // Electrical high = released.
    bool stable = true;
    bool ok = true;
    auto changed = Clock::now();
    const auto end = changed + std::chrono::seconds(30);
    std::cout << "Release the button, then press/release. Ctrl+C stops.\n";
    while (!stopped && Clock::now() < end) {
        gpio_v2_line_values values{};
        values.mask = 1;
        if (ioctl(request.fd, GPIO_V2_LINE_GET_VALUES_IOCTL, &values) < 0) {
            std::cerr << "Read value: " << std::strerror(errno) << '\n';
            ok = false;
            break;
        }
        const bool sample = (values.bits & 1) != 0;
        const auto now = Clock::now();
        if (sample != candidate) {
            candidate = sample;
            changed = now;
        }
        if (candidate != stable && now - changed >= std::chrono::milliseconds(25)) {
            stable = candidate;
            std::cout << (stable ? "Released\n" : "Pressed\n") << std::flush;
        }
        std::this_thread::sleep_for(std::chrono::milliseconds(5));
    }
    close(request.fd);
    close(chip);
    return ok ? 0 : 1;
}
g++ -std=c++17 -Wall -Wextra -Wpedantic -g -pthread gpio_button.cpp -o gpio_button
./gpio_button /dev/gpiochip0

Check: compilation succeeds and planning mode describes GPIO22, the sampling interval and debounce interval without opening the device.

4. Read actual button transitions

Only after checking the circuit and chip, apply:

./gpio_button /dev/gpiochip0 --apply

Release the button first, then press and release it a few times. The program runs for 30 seconds or until Ctrl+C. Expected: each deliberate stable press prints Pressed, and each stable release prints Released. Initial release need not print because it is the initial application state.

Mechanical contacts can bounce through several high/low transitions. Sampling slowly is not automatically debounce. This example instead keeps:

  • A candidate state from the most recent sample.
  • A timestamp updated whenever that candidate changes.
  • An accepted state changed only after the candidate remains unchanged for at least 25 ms.

Samples are taken about every 5 ms using a monotonic clock. Those are illustrative settings, not universal properties of every switch. Faster pulses can be missed; scheduling delays affect response time. For timing-critical inputs, consider kernel edge-event facilities and hardware conditioning rather than promising perfect detection.

The program requests input with pull-up, checks read errors, and releases descriptors on ordinary exit. It does not grant or permanently change account permissions.

Troubleshooting

Symptom First check
Always pressed Power off; check switch contact pairs and ground short
Never pressed Correct physical pin and opposite contact groups
Random transitions Pull-up accepted, common ground, wire/contact integrity
Repeated messages Contact stability and debounce requirements; do not merely lengthen polling without understanding
Permission error Device permissions/current groups
Busy or named-line mismatch Correct chip and existing consumer; do not override another driver

The code is compiled and its planning/error modes tested separately from hardware operation. The revised button circuit was not connected for this revision, so contact behaviour and the 25 ms setting require verification with your actual switch.

Practice before the next lesson

Work through a button trace on paper: the accepted released value is 1. Samples read 0 at 0 ms, 1 at 5 ms, then 0 at 10 ms and every sample thereafter. With a 25 ms stability threshold and 5 ms sampling, what is the earliest sample that can accept the final pressed value? No GPIO access is needed.

Hint and expected result

The last candidate change restarts the timer at 10 ms. With samples at 0, 5, 10, … ms, the earliest qualifying sample is 35 ms. This simplified trace assumes exact sample times; real scheduling may delay acceptance. A pull-up defines the released level, while debounce determines when a changed level is accepted.

Check your understanding and continue

Why does a released input read high? How is a stable-state interval different from a slow poll? Can you identify two switch contacts that are not permanently connected?

Next, learn Hardware PWM and a Passive Buzzer. Do not use this button polling loop to generate servo pulses.

Donate