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 void print_flags(unsigned long flags)
59 for (i = 0; i < ARRAY_SIZE(flagnames); i++) {
60 if (flags & flagnames[i].mask) {
63 fprintf(stdout, "%s", flagnames[i].name);
69 int list_device(const char *device_name)
71 struct gpiochip_info cinfo;
77 ret = asprintf(&chrdev_name, "/dev/%s", device_name);
81 fd = open(chrdev_name, 0);
84 fprintf(stderr, "Failed to open %s\n", chrdev_name);
85 goto exit_close_error;
88 /* Inspect this GPIO chip */
89 ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &cinfo);
92 perror("Failed to issue CHIPINFO IOCTL\n");
93 goto exit_close_error;
95 fprintf(stdout, "GPIO chip: %s, \"%s\", %u GPIO lines\n",
96 cinfo.name, cinfo.label, cinfo.lines);
98 /* Loop over the lines and print info */
99 for (i = 0; i < cinfo.lines; i++) {
100 struct gpioline_info linfo;
102 memset(&linfo, 0, sizeof(linfo));
103 linfo.line_offset = i;
105 ret = ioctl(fd, GPIO_GET_LINEINFO_IOCTL, &linfo);
108 perror("Failed to issue LINEINFO IOCTL\n");
109 goto exit_close_error;
111 fprintf(stdout, "\tline %2d:", linfo.line_offset);
113 fprintf(stdout, " \"%s\"", linfo.name);
115 fprintf(stdout, " unnamed");
116 if (linfo.consumer[0])
117 fprintf(stdout, " \"%s\"", linfo.consumer);
119 fprintf(stdout, " unused");
121 fprintf(stdout, " [");
122 print_flags(linfo.flags);
123 fprintf(stdout, "]");
125 fprintf(stdout, "\n");
131 perror("Failed to close GPIO character device file");
136 void print_usage(void)
138 fprintf(stderr, "Usage: lsgpio [options]...\n"
139 "List GPIO chips, lines and states\n"
140 " -n <name> List GPIOs on a named device\n"
141 " -? This helptext\n"
145 int main(int argc, char **argv)
147 const char *device_name = NULL;
151 while ((c = getopt(argc, argv, "n:")) != -1) {
154 device_name = optarg;
163 ret = list_device(device_name);
165 const struct dirent *ent;
168 /* List all GPIO devices one at a time */
169 dp = opendir("/dev");
176 while (ent = readdir(dp), ent) {
177 if (check_prefix(ent->d_name, "gpiochip")) {
178 ret = list_device(ent->d_name);
185 if (closedir(dp) == -1) {
186 perror("scanning devices: Failed to close directory");