Linux手柄开发

Linux手柄使用

Linux手柄驱动, 一般为joydev, 可使用modprobe -a joydev加载驱动模块。
手柄连接后的原始设备文件为/dev/hidraw*, 这个和具体手柄厂商的驱动相关。需要针对特定手柄进行操作优化可能需要使用这个设备。

通常情况下joydev手柄驱动提供一个通用的手柄接口供使用。joydev驱动创建的设备文件一般为/dev/input/js*。joydev驱动提供两种不同操作: 摇杆axes和按键button。

一般使用joydev提供的通用驱动。使用joydev一些手柄会将十字方向键当作摇杆类型,而不是button类型,比如我的手柄北通蝙蝠D2(BTP-BD2F),因此在一些游戏模拟器软件中不能识别十字按键。

实用工具

在Linux中提供几个实用工具:

jscal: 按键校准和按键重映射工具
jscal-restore
jscal-store
jstest: 读取按键状态,测试按键是否正确
jscal 按键映射示例:

An example output of -q looks like this ./jscal -q /dev/input/js0:
-u <n_of_axes,axmap1,axmap2,..., n_of_buttons,btnmap1,btnmap2, ...> --set-mappings Sets axis and button mappings to the
specified values
jscal -u
10,0,1,2,5,6,16,17,40,41,42,13,288,289,290,291,292,293,294,295,296,297,298,299,300
/dev/input/js0

The joystick has 10 axes and 13 buttons. If now one is to switch axes 2

jscal -u
10,0,1,5,2,6,16,17,40,41,42,13,288,289,290,291,292,293,294,295,296,297,298,299,300
/dev/input/js0

changing 2,5 to 5,2 on the line.
Remapping buttons is done the same way.
jstest示例:

jstest /dev/input/js0

手柄编程

#include <stdio.h>
#include <sys/stat.h>
#include <fcntl.h>

typedef unsigned int __u32;
typedef short __s16;
typedef unsigned char __u8;

struct js_event {
    __u32 time;     /* event timestamp in milliseconds */
    __s16 value;    /* value */
    __u8 type;      /* event type */
    __u8 number;    /* axis/button number */
};

#define JS_EVENT_BUTTON         0x01    /* button pressed/released */
#define JS_EVENT_AXIS           0x02    /* joystick moved */
#define JS_EVENT_INIT           0x80    /* initial state of device */

int main() {
    int fd = open("/dev/input/js0", O_RDONLY);
    struct js_event e;
    while(1) {
        read(fd, &e, sizeof(e));
        int type = JS_EVENT_BUTTON | JS_EVENT_INIT;
        switch(e.type) {
            case JS_EVENT_AXIS:
                printf("axis number: %d, value: %d, time: %d\n", e.number, e.value, e.time);
                break;
            case JS_EVENT_BUTTON:
                printf("btn: number: %d, value: %d, time: %d\n", e.number, e.value, e.time);
                break;
        }
    }
    close(fd);
    return 0;
}

开源库:

https://github.com/Tasssadar/libenjoy

参考:

https://www.kernel.org/doc/Documentation/input/joystick-api.txt

https://github.com/spotify/linux/blob/master/Documentation/input/joystick.txt

转自:

https://www.koyst.com/tech/172.html