From 6c7213d2eb93730b76759d2a2d8e72d1ff837f56 Mon Sep 17 00:00:00 2001 From: Heesub Shin Date: Mon, 24 Apr 2017 09:32:09 +0900 Subject: [PATCH] examples/sensorbd_demo: use poll() to detect button actions Rather than reading /dev/gpioX repeatedly with timeouts, using poll() would be better to show GPIO functionality. Change-Id: Id3318d821d4fcedd640161d3238a981f507109cf Signed-off-by: Heesub Shin --- .../examples/sensorbd_demo/examples/gpio_buttons.c | 79 +++++++++++++++------- 1 file changed, 54 insertions(+), 25 deletions(-) diff --git a/apps/examples/sensorbd_demo/examples/gpio_buttons.c b/apps/examples/sensorbd_demo/examples/gpio_buttons.c index f101224..597ff13 100644 --- a/apps/examples/sensorbd_demo/examples/gpio_buttons.c +++ b/apps/examples/sensorbd_demo/examples/gpio_buttons.c @@ -49,41 +49,70 @@ * POSSIBILITY OF SUCH DAMAGE. * ****************************************************************************/ +#include #include +#include +#include +#include + #include -static int gpio_read(int port) +void switch_main(int argc, char *argv[]) { - char value[4]; - static char buf[16]; - snprintf(buf, 16, "/dev/gpio%d", port); - int fd = open(buf, O_RDWR); + int i, j, nbtns, prev; + struct pollfd *poll_list; - ioctl(fd, GPIOIOC_SET_DIRECTION, GPIO_DIRECTION_IN); - read(fd, &value, sizeof(value)); + struct { + char *name; + char *devpath; + int fd; + } buttons[] = { + { "XEINT_0", "/dev/gpio57", }, + { "XEINT_1", "/dev/gpio58", }, + { "XEINT_2", "/dev/gpio59", }, + }; - close(fd); - return value[0] == '1'; -} + nbtns = sizeof(buttons) / sizeof(*buttons); -void switch_main(int argc, char *argv[]) -{ - // XEINT0 ~ XEINT2 - // gpio57 ~ gpio59 + poll_list = (struct pollfd *)malloc(sizeof(struct pollfd) * nbtns); - int i; - for (i = 0; i < 30; i++) { - if (gpio_read(57) == 0) { - printf("XEINT0 pressed\n"); - } - if (gpio_read(58) == 0) { - printf("XEINT1 pressed\n"); - } - if (gpio_read(59) == 0) { - printf("XEINT2 pressed\n"); + for (i = 0; i < nbtns; i++) { + printf("Opening %s(%s)...\n", buttons[i].devpath, buttons[i].name); + poll_list[i].fd = open(buttons[i].devpath, O_RDWR); + poll_list[i].events = POLLIN; + } + + printf("Polling buttons...\n"); + printf("(to terminate, press the same button twice in a row)\n"); + + prev = -1; + while (1) { + if (poll(poll_list, nbtns, 100)) { + for (j = 0; j < nbtns; j++) { + if (poll_list[j].revents & POLLIN) { + char buf[4]; + lseek(poll_list[j].fd, 0, SEEK_SET); + read(poll_list[j].fd, buf, sizeof(buf)); + printf("%s is %s\n", buttons[j].name, + buf[0] == '1' ? "rising" : "falling"); + + if (buf[0] == '1') { + if (prev == j) { + goto out; + } + prev = j; + } + } + } } + } - up_mdelay(500); +out: + for (i = 0; i < nbtns; i++) { + printf("Closing %s(%s)...\n", buttons[i].devpath, buttons[i].name); + close(poll_list[i].fd); } + + free(poll_list); } -- 2.7.4