main.c (1900B)
1 /* 2 2018 David DiPaola 3 licensed under CC0 (public domain, see https://creativecommons.org/publicdomain/zero/1.0/) 4 */ 5 6 #include <stdio.h> 7 8 #include <sys/types.h> 9 #include <sys/stat.h> 10 #include <fcntl.h> 11 12 #include <unistd.h> 13 14 #include <errno.h> 15 16 #include <linux/joystick.h> 17 18 int 19 main() { 20 printf("open() ..." "\n"); 21 int js_fd = -1; 22 char js_path[64]; 23 #define js_path_BASE "/dev/input/js" 24 for (int i=0; (i<=9 && js_fd<0); i++) { 25 snprintf(js_path, sizeof(js_path), js_path_BASE "%i", i); 26 js_fd = open(js_path, O_RDONLY | O_NONBLOCK); 27 } 28 if (js_fd < 0) { 29 fprintf(stderr, "ERROR: could not open any joystick devices at " js_path_BASE "X" "\n"); 30 return 1; 31 } 32 printf("open() success (%s)" "\n", js_path); 33 #undef js_path_BASE 34 35 printf("ioctl() %s :" "\n", js_path); 36 char c; 37 ioctl(js_fd, JSIOCGAXES, &c); printf("\t" "number of axes: %i" "\n", c); 38 ioctl(js_fd, JSIOCGBUTTONS, &c); printf("\t" "number of buttons: %i" "\n", c); 39 char s[128] = "Unknown"; 40 ioctl(js_fd, JSIOCGNAME(sizeof(s)), s); printf("\t" "name: %s" "\n", s); 41 42 printf("press HOME button to exit" "\n"); 43 int done = 0; 44 while (!done) { 45 usleep(16666); 46 47 struct js_event event; 48 ssize_t amount = read(js_fd, &event, sizeof(event)); 49 if (amount < (ssize_t)sizeof(event)) { 50 if (errno != EAGAIN) { 51 fprintf(stderr, "%s: read() expected %zi bytes but got %zi bytes" "\n", js_path, amount, sizeof(event)); 52 return 1; 53 } 54 else { 55 continue; 56 } 57 } 58 59 if (event.type & JS_EVENT_AXIS) { 60 printf("axis %i = %i" "\n", event.number, event.value); 61 } 62 else if (event.type & JS_EVENT_BUTTON) { 63 printf("button %i = %i" "\n", event.number, event.value); 64 if ((event.number == 8) && event.value) { 65 done = 1; 66 } 67 } 68 else if (event.type & JS_EVENT_INIT) { 69 printf("init" "\n"); 70 } 71 else { 72 printf("WARNING: event type unknown (0x%02X)" "\n", event.type); 73 } 74 } 75 76 close(js_fd); 77 } 78