In this code example we will be able to read a keyboard device input directly from/to /dev/input/eventX in Ubuntu with C++. You might want to change the default event device if that is not your keyboard. (Support for mouse etc. is not implemented)
You can find right device by:
# cat /proc/bus/input/devices
Find your keyboard and find a line like this "H: Handlers=kbd event5 ". Event5 tells you that right value for EVENT_DEVICE variable is "/dev/input/event5".
Run in terminal with:
# sudo ./<compiled_file> "/dev/input/event5"
Code:
#include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <fcntl.h> #include <stdio.h> #include <unistd.h> int main(int argc, char **argv) { int fd; if(argc < 2) { printf("usage: %s \n", argv[0]); return 1; } if ((getuid ()) != 0) printf ("You are not root! This may not work...n"); fd = open(argv[1], O_RDONLY); struct input_event ev; char name[256] = "Unknown"; ioctl (fd, EVIOCGNAME (sizeof (name)), name); printf ("Reading From : %s (%s)n", argv[1], name); while (1) { read(fd, &ev, sizeof(struct input_event)); if(ev.type == 1) { printf("key %i state %i\n", ev.code, ev.value); if(ev.value == 0) { printf(" : [key %i]\n ", ev.code); } } } return 0; }
In my case, the output of "cat /proc/bus/input/devices" looks like:
I: Bus=0019 Vendor=0000 Product=0001 Version=0000
N: Name="Power Button"
P: Phys=LNXPWRBN/button/input0
S: Sysfs=/devices/LNXSYSTM:00/LNXPWRBN:00/input/input2
U: Uniq=
H: Handlers=kbd event2
B: PROP=0
B: EV=3
B: KEY=100000 0 0 0
I: Bus=0011 Vendor=0001 Product=0001 Version=ab54
N: Name="AT Translated Set 2 keyboard"
P: Phys=isa0060/serio0/input0
S: Sysfs=/devices/platform/i8042/serio0/input/input3
U: Uniq=
H: Handlers=sysrq kbd event3
B: PROP=0
B: EV=120013
B: KEY=4 2000000 3803078 f800d001 feffffdf ffefffff ffffffff fffffffe
B: MSC=10
B: LED=7
So, the corresponding device is /dev/input/event3.
The output of this program is as follows:
$ sudo ./read_kbd /dev/input/event3
[sudo] password for charles:
: [key 28]
q : [key 16]
w : [key 17]
r : [key 19]
t : [key 20]
y : [key 21]
u : [key 22]
http://itech-planet.net/content/reading-device-input-directly-fromto-devinputeventx-ubuntu-c