Introduction

GPIO (General Purpose Input/Output) is a fundamental interface in embedded systems and Linux-based platforms. Linux provides multiple methods to control GPIOs, including the deprecated /sys/class/gpio/ interface and the modern libgpiod (GPIO character device) API. This document provides a comprehensive guide to managing GPIOs in Linux.

GPIO Interfaces in Linux

Linux provides three primary ways to manage GPIOs:

  1. Legacy Sysfs Interface (/sys/class/gpio/) - Deprecated but still present on some systems.
  2. GPIO Character Device (/dev/gpiochipX) - The recommended approach using libgpiod.
  3. Direct Kernel Access - Through kernel drivers or device tree configurations.

1. Sysfs GPIO Interface (Deprecated)

The sysfs-based interface was historically used to control GPIOs but has been marked as deprecated in favor of gpiod. If still available, it can be accessed via /sys/class/gpio/.

Exporting a GPIO

echo <gpio_number> > /sys/class/gpio/export

This creates a directory /sys/class/gpio/gpio<gpio_number>/.

Setting GPIO Direction

echo out > /sys/class/gpio/gpio<gpio_number>/direction

Or for input:

echo in > /sys/class/gpio/gpio<gpio_number>/direction

Controlling GPIO Value

For output:

echo 1 > /sys/class/gpio/gpio<gpio_number>/value  # Set HIGH
echo 0 > /sys/class/gpio/gpio<gpio_number>/value  # Set LOW

For input:

cat /sys/class/gpio/gpio<gpio_number>/value

Unexporting GPIO

echo <gpio_number> > /sys/class/gpio/unexport

2. GPIO Character Device Interface (libgpiod)

Modern Linux kernels (>=4.8) use a character device model for GPIO management, accessible via /dev/gpiochipX.

Installing libgpiod

sudo apt install gpiod libgpiod-dev

Listing Available GPIOs

gpioinfo

This shows GPIO chips and their pin assignments.

Exporting a GPIO

No need to manually export GPIOs when using gpiod.

Setting GPIO Direction and Controlling Value

  • Set GPIO as output and write a value:
# This sets GPIO 22 to HIGH for 1 second.
gpioset --mode=time --sec=1 gpiochip0 22=1
  • Read GPIO value:
gpioget gpiochip0 22
  • Monitor GPIO changes:
# This monitors GPIO 22 for 10 state changes.
gpiomon --num-events=10 gpiochip0 22

3. Direct Kernel-Level GPIO Management

For performance-sensitive applications, GPIOs can be managed directly via:

  • Device Tree (.dts) Configuration:
&gpio {
	my_gpio: gpio@22 {
		label = "custom_gpio";
		gpios = <&gpio0 22 GPIO_ACTIVE_HIGH>;
	};
};
  • Kernel Drivers (gpio.h):
struct gpio_desc *desc;
desc = gpiod_get(&pdev->dev, "custom_gpio", GPIOD_OUT_LOW);
gpiod_set_value(desc, 1);

Best Practices for GPIO Management

  1. Use libgpiod Instead of Sysfs - Future-proof applications by migrating to the character device interface.
  2. Use Device Tree for Static Configurations - Avoid runtime overhead by defining GPIO settings in the device tree.
  3. Ensure Proper Permissions - Non-root users may need udev rules to access /dev/gpiochipX.
  4. Debounce Input Signals - Use kernel debounce mechanisms for input signals.