2

I paired a bluetooth gamepad to my raspberry wich created two device files. One for directions and the other for the buttons. read a file works fine but i cant read both at the same time.

int main()
{

    char devname1[] = "/dev/input/event0";
    char devname2[] = "/dev/input/event2";
    int device1 = open(devname1, O_RDONLY);
    int device2 = open(devname2, O_RDONLY);
    struct input_event ev1;
    struct input_event ev2;

    while(1)
    {
        read(device1,&ev1, sizeof(ev1));
        read(device2,&ev2, sizeof(ev2));
        logger(ev1);    
        logger(ev2);                                   
    }
}

I created two file descriptors and read the data into two seperate structures. While outputing the gamepad output the programm sometimes print just from the one file and sometimes just from the second one.

Whats the propper way to read both files?

hyde
  • 60,639
  • 21
  • 115
  • 176
KingKoopa
  • 89
  • 2
  • 6
  • 2
    Show the code you have so far. It's not clear what problems you are asking readers to fix. – underscore_d Jul 13 '20 at 09:39
  • 3
    You can use `epoll` to monitor multiple file descriptors for changes. The basic usage is to create an epoll file descriptor using `epoll_create()`, and then register the file descriptors of your input device(s) with `epoll_ctl()`. Once that's done, you can wait for events in your main loop using `epoll_wait()` – Felix G Jul 13 '20 at 10:22
  • 1
    Each read() call might block until it gets data. You might want to use non-blocking read. – th33lf Jul 13 '20 at 10:39
  • 1
    Check out https://stackoverflow.com/questions/27247/could-you-recommend-some-guides-about-epoll-on-linux – hyde Jul 13 '20 at 10:43
  • 1
    @th33lf Non blocking reads are rather inefficient for something like this though, because the application will just constantly waste CPU cycles doing absolutely nothing while waiting for some user input. So unless OP wants to heat their appartment with this application, i would recommend against using non-blocking reads. – Felix G Jul 13 '20 at 10:50
  • 1
    @FelixG Regular `poll` should be good enough for this use case. – user253751 Jul 13 '20 at 10:51
  • 1
    @user253751 well, i just tend to default to using epoll because "why not" ;-) but of course `poll` will work just fine (and might even be preferable, if portability is a concern) – Felix G Jul 13 '20 at 10:57
  • 1
    @FelixG The reason to default to poll, IMO, is that it's much simpler. epoll can be used when you have a lot of file descriptors to measure, not just 2, or you're writing a library to wrap it. – user253751 Jul 13 '20 at 11:06
  • cool thanks for the input i will take a closer look at the polling stuff – KingKoopa Jul 13 '20 at 13:31
  • @FelixG I'd also add a nanosleep() in the loop depending on how frequently I wanted to sample the inputs. But of course, I agree waiting on a semaphore is the cleaner solution. – th33lf Jul 14 '20 at 14:43

0 Answers0