Ok so I'm back, my code now compiles successfully, it just does nothing when I run it, not even printing "Joystick Open Successful". I can't see any obvious reasons for this, any ideas?
Again excuse my commenting:
#include <stdio.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <linux/joystick.h> /* lots of included headers because */
/* I wasn't sure which I needed! */
#define JS_EVENT_AXIS 0x02 /* joystick moved */
int open_joystick(int fd) { /* function to open the joystick */
fd = open ("/dev/js0", O_RDONLY | O_NONBLOCK); /* setting fd to open the joystick */
if (fd >= 0) { /* in non blocking mode */
printf("Open Joystick Successful");
}
return fd; /* functions like to return something */
}
void read_joystick_thrust_axis(int fd, struct js_event js) { /* another function, including the integer fd, */
/* the structure js
while (read (fd, &js, sizeof(js)) > 0) { /* while there is a joystick event to read */
if (js.type == JS_EVENT_AXIS && js.number == 1){ /* and if that event is an axis event */
/* and if that event is on the right axis */
printf ("Thrust Reading: %8hd\n", js.value); /* print the values of it */
}
}
int main() {
int fd;
struct js_event js;
fd = open_joystick(fd);
while (1) {
read_joystick_thrust_axis(fd, js);
}
return 0;
}
This lines are wrong:
if (fd < 0) {
printf("Open Joystick Successful");
open
returns -1
when it fails, or something >=0
if it succeeds, so you have the logic wrong.
Probably your open()
is failing because you lack permissions to open this device. Or maybe it does not exist... (/dev/input/js0
?). Just check errno
to be sure:
if (fd < 0)
perror("/dev/js0");