-
Notifications
You must be signed in to change notification settings - Fork 17
/
joydev.cpp
90 lines (82 loc) · 2.07 KB
/
joydev.cpp
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
#include <stdlib.h>
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/ioctl.h>
#include <fcntl.h>
#include <unistd.h>
#include <linux/joystick.h>
#include <linux/input.h>
struct Joystick
{
bool connected;
char buttonCount;
short* buttonStates;
char axisCount;
short* axisStates;
char name[128];
int file;
};
Joystick openJoystick(const char* fileName)
{
Joystick j = {0};
int file = open(fileName, O_RDONLY | O_NONBLOCK);
if (file != -1)
{
ioctl(file, JSIOCGBUTTONS, &j.buttonCount);
j.buttonStates = (short*)calloc(j.buttonCount, sizeof(short));
ioctl(file, JSIOCGAXES, &j.axisCount);
j.axisStates = (short*)calloc(j.axisCount, sizeof(short));
ioctl(file, JSIOCGNAME(sizeof(j.name)), j.name);
j.file = file;
j.connected = true;
}
return j;
}
void readJoystickInput(Joystick* joystick)
{
while (1)
{
js_event event;
int bytesRead = read(joystick->file, &event, sizeof(event));
if (bytesRead == 0 || bytesRead == -1) return;
if (event.type == JS_EVENT_BUTTON && event.number < joystick->buttonCount) {
joystick->buttonStates[event.number] = event.value;
}
if (event.type == JS_EVENT_AXIS && event.number < joystick->axisCount) {
joystick->axisStates[event.number] = event.value;
}
}
}
int main()
{
const unsigned int maxJoysticks = 32;
Joystick joysticks[maxJoysticks] = {0};
char fileName[32];
for (unsigned int i=0; i<maxJoysticks; ++i)
{
sprintf(fileName, "/dev/input/js%d", i);
joysticks[i] = openJoystick(fileName);
}
while (1)
{
for (unsigned int i=0; i<maxJoysticks; ++i)
{
if (joysticks[i].connected)
{
readJoystickInput(&joysticks[i]);
printf("%s - Axes: ", joysticks[i].name);
for (char axisIndex=0; axisIndex<joysticks[i].axisCount; ++axisIndex) {
printf("%d:% 6d ", axisIndex, joysticks[i].axisStates[axisIndex]);
}
printf("Buttons: ");
for (char buttonIndex=0; buttonIndex<joysticks[i].buttonCount; ++buttonIndex) {
if (joysticks[i].buttonStates[buttonIndex]) printf("%d ", buttonIndex);
}
printf("\n");
}
}
fflush(stdout);
usleep(16000);
}
}