Last active
September 1, 2024 20:33
-
-
Save fabiocolacio/8fa683a31b844717e58dd4023b63f1f9 to your computer and use it in GitHub Desktop.
Joystick Test Code for Linux
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
#include <stdlib.h> | |
#include <unistd.h> | |
#include <fcntl.h> | |
#include <sys/ioctl.h> | |
#include <linux/joystick.h> | |
/* | |
* Compiles on linux systems only! | |
* | |
* Compile it with: | |
* | |
* gcc joy_tester.c -o joy_tester | |
* | |
* This program infinitely reads joystick events from /dev/input/jsN | |
* and outputs them to STDOUT. | |
*/ | |
int main(int argc, char** argv) { | |
struct js_event msg; | |
char* joystick; | |
char* event_type = "none"; | |
// joystick metadata | |
char joystick_name[1024] = "unknown"; | |
unsigned char num_buttons = 0; | |
unsigned char num_axes = 0; | |
// Choose a device file to read, or default to /dev/input/js0 | |
if (argc < 2) { | |
joystick = "/dev/input/js0"; | |
} else { | |
joystick = argv[1]; | |
} | |
// Open the device file for reading | |
int fd = open(joystick, O_RDONLY); | |
// Get the name of the joystick | |
ioctl(fd, JSIOCGNAME(sizeof joystick_name), joystick_name); | |
// Get the number of axes on the joystick | |
ioctl(fd, JSIOCGAXES, &num_axes); | |
// Get the number of buttons on the joystick | |
ioctl(fd, JSIOCGBUTTONS, &num_buttons); | |
// Infinitely read joystick events from the device file | |
while (1) { | |
if (read(fd, &msg, sizeof(struct js_event)) != sizeof(struct js_event)) { | |
printf("Could not read from joystick.\n"); | |
exit(1); | |
} else { | |
if (msg.type == JS_EVENT_BUTTON) { | |
event_type = "button"; | |
} else if (msg.type == JS_EVENT_AXIS) { | |
event_type = "axis"; | |
} else if (msg.type == JS_EVENT_INIT) { | |
event_type = "initialization"; | |
} | |
printf("Action Performed!\n" | |
" joystick name: %s\n" | |
" number of buttons: %u\n" | |
" number of axes: %u\n" | |
" value: %d\n" | |
" event type: %s\n" | |
" axis/button number: %u\n" | |
" timestamp: %u\n" | |
"===\n" | |
, joystick_name | |
, num_buttons | |
, num_axes | |
, msg.value | |
, event_type | |
, msg.number | |
, msg.time); | |
usleep(10000); | |
} | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment