</>EmbeddedInterview

How do you access GPIO from Linux user space?

MediumEmbedded Linux & Boot

Short answer: Use the GPIO character device (/dev/gpiochipN) through libgpiod and its command-line tools (gpiodetect, gpioinfo, gpioget, gpioset, gpiomon). The old sysfs interface (/sys/class/gpio) is deprecated. For production, describe fixed-function pins in the device tree and let a kernel driver own them.

Command-line examples (libgpiod v2 syntax)

gpiodetect                         # list GPIO chips
gpioinfo gpiochip0                 # line names, direction, consumers
gpioget -c gpiochip0 17            # read line 17
gpioset -c gpiochip0 18=1          # drive line 18 high (holds it while running)
gpiomon -c gpiochip0 -e rising 23  # wait for rising edges

C with libgpiod v2 (sketch)

#include <gpiod.h>

struct gpiod_chip *chip = gpiod_chip_open("/dev/gpiochip0");
struct gpiod_line_settings *s = gpiod_line_settings_new();
gpiod_line_settings_set_direction(s, GPIOD_LINE_DIRECTION_OUTPUT);
struct gpiod_line_config *lc = gpiod_line_config_new();
unsigned int offset = 18;
gpiod_line_config_add_line_settings(lc, &offset, 1, s);
struct gpiod_line_request *req = gpiod_chip_request_lines(chip, NULL, lc);
gpiod_line_request_set_value(req, 18, GPIOD_LINE_VALUE_ACTIVE);

Why sysfs was deprecated

  • Global GPIO numbers that change between kernel versions and boards.
  • No ownership: any process could change any pin, and an exported pin stayed configured after the program crashed.
  • Edge events through poll() on a value file were awkward and could lose events.
  • The character device gives named lines, per-process ownership (released automatically when the process exits), timestamps on events, bias (pull-up/down) and debounce settings.

Production advice

  • LEDs: gpio-leds driver → /sys/class/leds/... (with triggers like heartbeat).
  • Buttons: gpio-keys → a standard input device (/dev/input/eventN).
  • Resets and enables for chips: let the chip's kernel driver request them via reset-gpios/enable-gpios in the device tree.
  • Use user-space GPIO for prototyping, test equipment and truly application-specific signals.

Timing limits: user-space GPIO toggling has jitter (scheduling, syscalls). For precise waveforms use PWM, SPI or a timer peripheral, a kernel driver, or a coprocessor (e.g. the Cortex-M core on an i.MX8M or STM32MP1).