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:
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.

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:
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.
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:
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.