I am attempting to write a code to read a joystick axis values, which i eventually hope to be able to use the values for controlling motors. After copious amounts of trying to figure out C and how on earth to use the joystick api I wrote this code. to start with it came only with one variable undeclared error then as I improved code, making it more readable and easier to understand I got another one of the same when I went to compile it hoping the first would have gone away! This is my code (excuse the 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; /* fd declared I thought */
fd = open ("/dev/js0", O_RDONLY | O_NONBLOCK);
return fd; /* code likes something to return */
}
int read_joystick_thrust_axis(struct js_event js) /* declare r_j_t_a variable and the js instance */
while (1) { /* loop forever */
while (read (fd, &js, sizeof(js)) > 0) { /* while there is an event */
if (js_event.type == JS_EVENT_AXIS) { /* and if that is an axis event */
if (js_event.number == 1) { /* and if that event is on the right axis */
printf ("Joystick at %8hb\n", js.value); /* print that instance of the joysticks value */
}
}
}
}
return 0; } /* keeping C happy by returning something */
And the errors i get back from gcc are:
pi@raspberrypi ~/rc $ gcc joystick.c
joystick.c: In function ‘read_joystick_thrust_axis’:
joystick.c:24:16: error: ‘fd’ undeclared (first use in this function)
joystick.c:24:16: note: each undeclared identifier is reported only once for each function it appears in
joystick.c:25:8: error: ‘js_event’ undeclared (first use in this function)
Could someone please explain why I am getting these errors and suggest a fix? Thank you in advance.
open_joystick
sets fd
, but fd
is local to open_joystick
, and therefore not readable by read_joystick_thrust_axis
. Convert read_joystick_thrust_axis
to allow fd
to be passed as an argument, and pass the return value of open_joystick
, like this:
Change:
int read_joystick_thrust_axis(struct js_event js)
to
int read_joystick_thrust_axis(int fd, struct js_event js)
Then when you call it (from main
or whatever), do
int fd;
fd = open_joystick();
...
int read_joystick_thrust_access (fd, whatever);
Re the js_event
error, the variable is named js
, and is of type struct js_event
. Therefore you want to refer to js.type
not js_event.type
.