1 // SPDX-License-Identifier: GPL-2.0-only
3 * lsgpio - example on how to list the GPIO lines on a system
5 * Copyright (C) 2015 Linus Walleij
8 * lsgpio <-n device-name>
21 #include <sys/ioctl.h>
22 #include <linux/gpio.h>
24 #include "gpio-utils.h"
31 struct gpio_flag flagnames[] = {
34 .mask = GPIOLINE_FLAG_KERNEL,
38 .mask = GPIOLINE_FLAG_IS_OUT,
42 .mask = GPIOLINE_FLAG_ACTIVE_LOW,
46 .mask = GPIOLINE_FLAG_OPEN_DRAIN,
49 .name = "open-source",
50 .mask = GPIOLINE_FLAG_OPEN_SOURCE,
54 .mask = GPIOLINE_FLAG_BIAS_PULL_UP,
58 .mask = GPIOLINE_FLAG_BIAS_PULL_DOWN,
61 .name = "bias-disabled",
62 .mask = GPIOLINE_FLAG_BIAS_DISABLE,
66 void print_flags(unsigned long flags)
71 for (i = 0; i < ARRAY_SIZE(flagnames); i++) {
72 if (flags & flagnames[i].mask) {
75 fprintf(stdout, "%s", flagnames[i].name);
81 int list_device(const char *device_name)
83 struct gpiochip_info cinfo;
89 ret = asprintf(&chrdev_name, "/dev/%s", device_name);
93 fd = open(chrdev_name, 0);
96 fprintf(stderr, "Failed to open %s\n", chrdev_name);
97 goto exit_close_error;
100 /* Inspect this GPIO chip */
101 ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &cinfo);
104 perror("Failed to issue CHIPINFO IOCTL\n");
105 goto exit_close_error;
107 fprintf(stdout, "GPIO chip: %s, \"%s\", %u GPIO lines\n",
108 cinfo.name, cinfo.label, cinfo.lines);
110 /* Loop over the lines and print info */
111 for (i = 0; i < cinfo.lines; i++) {
112 struct gpioline_info linfo;
114 memset(&linfo, 0, sizeof(linfo));
115 linfo.line_offset = i;
117 ret = ioctl(fd, GPIO_GET_LINEINFO_IOCTL, &linfo);
120 perror("Failed to issue LINEINFO IOCTL\n");
121 goto exit_close_error;
123 fprintf(stdout, "\tline %2d:", linfo.line_offset);
125 fprintf(stdout, " \"%s\"", linfo.name);
127 fprintf(stdout, " unnamed");
128 if (linfo.consumer[0])
129 fprintf(stdout, " \"%s\"", linfo.consumer);
131 fprintf(stdout, " unused");
133 fprintf(stdout, " [");
134 print_flags(linfo.flags);
135 fprintf(stdout, "]");
137 fprintf(stdout, "\n");
143 perror("Failed to close GPIO character device file");
148 void print_usage(void)
150 fprintf(stderr, "Usage: lsgpio [options]...\n"
151 "List GPIO chips, lines and states\n"
152 " -n <name> List GPIOs on a named device\n"
153 " -? This helptext\n"
157 int main(int argc, char **argv)
159 const char *device_name = NULL;
163 while ((c = getopt(argc, argv, "n:")) != -1) {
166 device_name = optarg;
175 ret = list_device(device_name);
177 const struct dirent *ent;
180 /* List all GPIO devices one at a time */
181 dp = opendir("/dev");
188 while (ent = readdir(dp), ent) {
189 if (check_prefix(ent->d_name, "gpiochip")) {
190 ret = list_device(ent->d_name);
197 if (closedir(dp) == -1) {
198 perror("scanning devices: Failed to close directory");