2022-10-25

How to read /dev/input/mice more accurately?

I'm writing a program to read /dev/input/mice to get relative x,y positions and get the absolute distance the cursor moves. If I move my mouse at a normal speed starting at the center of the screen, the result is pretty accurate(960). However, if I move my mouse really fast, the absolute distance is not accurate.

#include <stdlib.h>
#include <fcntl.h>
#include <unistd.h>
#include <sys/time.h>
#include <sys/types.h>
#include <sys/select.h>

int main() {
    signed char x, y;
    signed char buf[6];
    int fd;
    fd_set readfds;
    int screen_x = 1920;
    int screen_y = 1080;
    int x_total = 0, y_total = 0;

    // Create the file descriptor
    fd = open("/dev/input/mice", O_RDONLY);
    if (fd == -1) {
        printf("Error Opening /dev/input/mice\n");
        return 1;
    }

    printf("sizeof(buf): %d\n", sizeof(buf));

    // Loop that reads relative position in /device/input/mice
    while(1) {
        // Set the file descriptor
        FD_ZERO(&readfds);
        FD_SET(fd,&readfds);
        select(fd+1, &readfds, NULL, NULL, NULL);

        // Check if the fd is set successfully
        if(FD_ISSET(fd,&readfds)) { 
            // Check if reading fails
            if(read(fd, buf, sizeof(buf)) <= 0) {  
                continue;  
            }

            // Relative positions
            x = buf[1];
            y = buf[2];
            printf("x=%d, y=%d\n", x, y);
            // Assume that mouse starts at the center
            x_total += x;
            y_total += y;
            printf("x_total: %d; y_total: %d\n", x_total, y_total);
        }  
    }
    close(fd);
    return 0;
}

I use xdotool mousemove 960 540 to get the cursor at the center and then run the program. Output is something like:

x_total: 309; y_total:0
x= 3, y=2
x_total:312; y_total:2

So if I move the cursor from the center towards the right edge really fast, at the time the cursor reaches the right edge, x_total is going to be somewhere around 500 which should've been 960.



No comments:

Post a Comment