C++ – Use the mouse for non-mouse input

Use the mouse for non-mouse input… here is a solution to the problem.

Use the mouse for non-mouse input

So my problem today is related to connecting a USB mouse plugged into a Linux machine. However, I don’t want the mouse to have any traditional impact on the X environment – I just want to be able to take advantage of the encoder embedded in it through the raw input. So that’s my question.

How do I get low-level but meaningful data from an alternate mouse device in C++ in Linux? Specifically, I would like to know the relative position or at least encoder counts along the x- and y-axes.

Solution

I did something similar for a USB barcode reader that appears as a HID keyboard.

In recent kernels, there will be a mouse event device in /dev/input/event*. If you open it and get it using EVIOCGRAB ioctl(), it will not send mouse events to any other application. You can then read the event directly from the mouse – see the evdev interface documentation in Documentation/input/input.txt. In a Linux source code distribution.

When you read from the event device, you get an integer input event of the following form:

struct input_event {
    struct timeval time;
    unsigned short type;
    unsigned short code;
    unsigned int value;
};

( struct input_event and subsequent macros are defined in linux/input.h.)

The event you are interested in will have input_event.type == EV_REL (relative motion event), input_event.code members will be similar to REL_X (representing the X axis – see linux/input.h file for a complete list) and input_event.value will be the displacement.

As the other answer suggests, you don’t need to implement the HID protocol yourself.

Related Problems and Solutions