未声明变量的操纵杆代码错误

时间:2014-02-25 20:22:00

标签: c linux compiler-errors joystick

我正在尝试编写一个代码来读取操纵杆轴值,我最终希望能够使用这些值来控制电机。经过大量尝试弄清楚C以及如何使用操纵杆api我编写了这段代码。从它开始只有一个变量未声明的错误,然后我改进代码,使它更易读和更容易理解我有另一个相同的当我去编译它希望第一个会有走了! 这是我的代码(请原谅评论):

#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 */

我从gcc回来的错误是:

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)

有人可以解释为什么我会收到这些错误并建议修复? 提前谢谢。

1 个答案:

答案 0 :(得分:0)

open_joystick设置了fd,但fdopen_joystick的本地设置,因此read_joystick_thrust_axis无法读取。将read_joystick_thrust_axis转换为允许fd作为参数传递,并传递open_joystick的返回值,如下所示:

变化:

int read_joystick_thrust_axis(struct js_event js)

int read_joystick_thrust_axis(int fd, struct js_event js)

然后当你打电话时(来自main或其他),做

int fd;
fd = open_joystick();
...
int read_joystick_thrust_access (fd, whatever);

重新js_event错误,该变量名为js,类型为struct js_event。因此,您要引用js.type而不是js_event.type