2014-02-25 45 views
0

我正在嘗試編寫代碼來讀取操縱桿軸的值,我最終希望能夠使用這些值來控制電機。經過大量的努力找出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後面的錯誤是:

[email protected] ~/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

'fd'在'open_joystick'中聲明,其詞法範圍是'open_joystick'的範圍。 – ouah

回答

0

open_joystickfd,但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

+0

非常感謝你現在更有意義!如何將'read_joystick_thrust _axis'轉換爲允許'fd'作爲參數傳遞?我不確定我是否理解你在與你談論什麼/你在哪裏談論「通過'open_joystick'的回報價值'」你可以嘗試重新解釋嗎?對不起,這裏有一個新手。 –

+0

我修改了答案。 – abligh

+0

謝謝,好吧,我想我現在明白了!那麼從主體調用它的那一點只會用到,如果我想從另一個函數調用它呢?對不起 –