| USB HID for Linux USB | ||
|---|---|---|
| <<< Previous | The event interface | Next >>> |
So far, all of the discussion has been about what the device is capable of (eg whether the device has a trigger button). In this section, we will see how to actually get user input from the device (eg, whether the trigger button has been pressed by the user).
The event interface provides this information using a read function call. The result of that read is one or more input_event structures, and the return value is the number of bytes read.
The input_event structure is defined as
struct input_event {
struct timeval time;
unsigned short type;
unsigned short code;
unsigned int value;
}; |
The time element is a normal timeval structure, and contains the time that the event occurred. The type element is the type of feature that is being reported (for example, EV_KEY, EV_REL, EV_ABS or EV_MSC). The code element contains the particular feature that is being reported (for example, KEY_SPACE, KEY_F1, REL_WHEEL or ABS_X). The value is the value of that particular feature (for example, 0 or 1 for a key, or some other integer value for a relative or absolute axis).
Let's look at an example of the read interface.
![]() | About this example |
|---|---|
This example is intentionally a code fragment, and is not complete, nor is it meant to show good programming style. A complete form of this example (that will compile with gcc -Wall -W) is provided in the second part of this document. |
Example 7. read example
struct input_event ev;
…
while (1)
{
read(fd, &ev, sizeof(struct input_event));
printf("Event: time %ld.%06ld, type %d, code %d, value %d\n",
ev.time.tv_sec, ev.time.tv_usec, ev.type,
ev.code, ev.value);
} |
This example shows a busy loop over the particular event device. The read call waits for the event (assuming it was opened with O_NONBLOCK), and then prints out the various values of the event.
Note that this read interface has all the normal characteristics of a character device. This means that you don't need to use a busy loop. You can just wait till your program needs some input from the device, and then perform the read call. In addition, if you are interested in the input from a number of devices, you can use the poll and select functions to wait on a number of open devices at the same time.
For more information on the read, open, select or poll functions, refer to the applicable man pages, or any good C programming book.
| <<< Previous | Home | Next >>> |
| Determining the device capabilities and features | Up | Sending information to the device |