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"
29 int list_device(const char *device_name)
31 struct gpiochip_info cinfo;
36 ret = asprintf(&chrdev_name, "/dev/%s", device_name);
40 fd = open(chrdev_name, 0);
43 fprintf(stderr, "Failed to open %s\n", chrdev_name);
44 goto free_chrdev_name;
47 /* Inspect this GPIO chip */
48 ret = ioctl(fd, GPIO_GET_CHIPINFO_IOCTL, &cinfo);
51 fprintf(stderr, "Failed to retrieve GPIO fd\n");
53 perror("Failed to close GPIO character device file");
55 goto free_chrdev_name;
57 fprintf(stdout, "GPIO chip: %s, %u GPIO lines\n",
58 cinfo.name, cinfo.lines);
60 if (close(fd) == -1) {
62 goto free_chrdev_name;
72 void print_usage(void)
74 fprintf(stderr, "Usage: lsgpio [options]...\n"
75 "List GPIO chips, lines and states\n"
76 " -n <name> List GPIOs on a named device\n"
81 int main(int argc, char **argv)
83 const char *device_name;
87 while ((c = getopt(argc, argv, "n:")) != -1) {
99 ret = list_device(device_name);
101 const struct dirent *ent;
104 /* List all GPIO devices one at a time */
105 dp = opendir("/dev");
112 while (ent = readdir(dp), ent) {
113 if (check_prefix(ent->d_name, "gpiochip")) {
114 ret = list_device(ent->d_name);
121 if (closedir(dp) == -1) {
122 perror("scanning devices: Failed to close directory");