我正在尝试编写代码来读取操纵杆轴值,我最终希望能够使用这些值来控制电机。经过大量尝试弄清楚 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)
有人可以解释一下为什么我会收到这些错误并提出修复建议吗? 预先感谢您。
最佳答案
open_joystick
设置 fd
,但 fd
是 open_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
。
关于c - 未声明变量的操纵杆代码错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22025306/