各式各样的键盘

现在市场上也出现了很多种USB连接的键盘等。虽然各自的规格并不相同,但是也无须担心。Linux的input子系统中准备了十分方便的接口。通过访问/dev/input/eventN文件,就可以从用户空间控制键盘(N为数字)。查找已分配给键盘的事件文件时,可以使用下列命令从/proc/bus/input/devices寻找键盘的设备。


cat/proc/bus/input/devices

……

I:Bus=0011 Vendor=0001 Product=0001 Version=ab41

N:Name="AT Translated Set 2 keyboard"

P:Phys=isa0060/serio0/input0

S:Sysfs=/devices/platform/i8042/serio0/input/input3

U:Uniq=

H:Handlers=kbd event3

B:EV=120013

B:KEY=4 2000000 3803078 f800d001 feffffdf ffefffff ffffffff fffffffe

B:MSC=10

B:LED=7

……


从Handlers入口可以看出event3为键盘用的事件文件。EV入口是表示可操作事件的位图(bitmap)。当EV入口中有LED的位时,显示LED入口。如果有LED入口,表示可以使用事件文件对LED进行操作。LED入口为位图,各个位表示所支持的LED。LED的位图意义如下。


define LED_NUML 0x00

define LED_CAPSL 0x01

define LED_SCROLLL 0x02

define LED_COMPOSE 0x03

define LED_KANA 0x04

define LED_SLEEP 0x05

define LED_SUSPEND 0x06

define LED_MUTE 0x07

define LED_MISC 0x08

define LED_MAIL 0x09

define LED_CHARGING 0x0a


具体来说,可以用以下这些代码来控制。在第34行打开参数文件。将/dev/input/eventN作为write函数的参数。通过向事件文件写入,可以点亮或熄灭LED。


1#include<stdlib.h>

2#include<stdio.h>

3#include<sys/types.h>

4#include<sys/stat.h>

5#include<fcntl.h>

6#include<unistd.h>

7#include<sys/ioctl.h>

8#include<stdint.h>

9#include<errno.h>

10#include<linux/input.h>

11

12#define OFF 0

13#define ON 1

14

15 void usage(char**argv)

16{

17 printf("Usage:%s<event-device>\n",argv[0]);

18 printf("e.g.%s/dev/input/evdev0\n",argv[0]);

19 return;

20}

21

22 int main(int argc, char**argv)

23{

24

25 int fd;

26 int ret=0;

27 struct input_event ev;

28

29 if(argc!=2){

30 usage(argv);

31 exit(1);

32}

33

34 if((fd=open(argv[1],O_WRONLY))<0){

35 perror("evdev file open");

36 usage(argv);

37 exit(1);

38}

39

40/Turn on a LED of CAPS_LOCK/

41 ev.type=EV_LED;

42 ev.value=ON;

43 ev.code=LED_CAPSL;

44 ret=write(fd,&ev, sizeof(struct input_event));

45 usleep(100000);

46/Turn off a LED of CAPS_LOCK/

47 ev.value=OFF;

48 ret=write(fd,&ev, sizeof(struct input_event));

49 usleep(100000);

50

51/Turn on a LED of NUM_LOCK/

52 ev.code=LED_NUML;

53 ev.value=ON;

54 ret=write(fd,&ev, sizeof(struct input_event));

55 usleep(100000);

56/Turn off a LED of NUM_LOCK/

57 ev.value=OFF;

58 ret=write(fd,&ev, sizeof(struct input_event));

59 usleep(100000);

60

61/Turn on a LED of SCROLL_LOCK/

62 ev.code=LED_SCROLLL;

63 ev.value=ON;

64 ret=write(fd,&ev, sizeof(struct input_event));

65 usleep(100000);

66/Turn off a LED of SCROLL_LOCK/

67 ev.value=OFF;

68 ret=write(fd,&ev, sizeof(struct input_event));

69 usleep(100000);

70

71 close(fd);

72

73 return 0;

74}