2 * lsgpio - example on how to list the GPIO lines on a system
4 * Copyright (C) 2015 Linus Walleij
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License version 2 as published by
8 * the Free Software Foundation.
11 * lsgpio <-n device-name>
24 #include <sys/ioctl.h>
25 #include <linux/gpio.h>
27 #include "gpio-utils.h"
34 struct gpio_flag flagnames
[] = {
37 .mask
= GPIOLINE_FLAG_KERNEL
,
41 .mask
= GPIOLINE_FLAG_IS_OUT
,
45 .mask
= GPIOLINE_FLAG_ACTIVE_LOW
,
49 .mask
= GPIOLINE_FLAG_OPEN_DRAIN
,
52 .name
= "open-source",
53 .mask
= GPIOLINE_FLAG_OPEN_SOURCE
,
57 void print_flags(unsigned long flags
)
62 for (i
= 0; i
< ARRAY_SIZE(flagnames
); i
++) {
63 if (flags
& flagnames
[i
].mask
) {
66 fprintf(stdout
, "%s", flagnames
[i
].name
);
72 int list_device(const char *device_name
)
74 struct gpiochip_info cinfo
;
80 ret
= asprintf(&chrdev_name
, "/dev/%s", device_name
);
84 fd
= open(chrdev_name
, 0);
87 fprintf(stderr
, "Failed to open %s\n", chrdev_name
);
88 goto exit_close_error
;
91 /* Inspect this GPIO chip */
92 ret
= ioctl(fd
, GPIO_GET_CHIPINFO_IOCTL
, &cinfo
);
95 perror("Failed to issue CHIPINFO IOCTL\n");
96 goto exit_close_error
;
98 fprintf(stdout
, "GPIO chip: %s, \"%s\", %u GPIO lines\n",
99 cinfo
.name
, cinfo
.label
, cinfo
.lines
);
101 /* Loop over the lines and print info */
102 for (i
= 0; i
< cinfo
.lines
; i
++) {
103 struct gpioline_info linfo
;
105 memset(&linfo
, 0, sizeof(linfo
));
106 linfo
.line_offset
= i
;
108 ret
= ioctl(fd
, GPIO_GET_LINEINFO_IOCTL
, &linfo
);
111 perror("Failed to issue LINEINFO IOCTL\n");
112 goto exit_close_error
;
114 fprintf(stdout
, "\tline %2d:", linfo
.line_offset
);
116 fprintf(stdout
, " \"%s\"", linfo
.name
);
118 fprintf(stdout
, " unnamed");
119 if (linfo
.consumer
[0])
120 fprintf(stdout
, " \"%s\"", linfo
.consumer
);
122 fprintf(stdout
, " unused");
124 fprintf(stdout
, " [");
125 print_flags(linfo
.flags
);
126 fprintf(stdout
, "]");
128 fprintf(stdout
, "\n");
134 perror("Failed to close GPIO character device file");
139 void print_usage(void)
141 fprintf(stderr
, "Usage: lsgpio [options]...\n"
142 "List GPIO chips, lines and states\n"
143 " -n <name> List GPIOs on a named device\n"
144 " -? This helptext\n"
148 int main(int argc
, char **argv
)
150 const char *device_name
;
154 while ((c
= getopt(argc
, argv
, "n:")) != -1) {
157 device_name
= optarg
;
166 ret
= list_device(device_name
);
168 const struct dirent
*ent
;
171 /* List all GPIO devices one at a time */
172 dp
= opendir("/dev");
179 while (ent
= readdir(dp
), ent
) {
180 if (check_prefix(ent
->d_name
, "gpiochip")) {
181 ret
= list_device(ent
->d_name
);
188 if (closedir(dp
) == -1) {
189 perror("scanning devices: Failed to close directory");