input子系统基础之按键2——input设备应用层编程实践

以下内容源于朱有鹏《物联网大讲堂》课程的学习,如有侵权,请告知删除。


一、input设备应用层编程实践1

1、确定设备文件名

(1)应用层操作驱动有2条路:/dev目录下的设备文件,/sys目录下的属性文件

(2)input子系统用的/dev目录下的设备文件,具体一般都是在 /dev/input/eventn

(3)用cat命令来确认某个设备文件名对应哪个具体设备。

  • 实测的键盘是event1,而鼠标是event3。


2、标准接口打开并读取文件


3、解析struct input_event

[cpp]  view plain  copy
  1. #include <stdio.h>  
  2. #include <sys/types.h>  
  3. #include <sys/stat.h>  
  4. #include <fcntl.h>  
  5. #include <linux/input.h>  
  6. #include <string.h>  
  7.   
  8.   
  9. #define DEVICE_KEY          "/dev/input/event1"  
  10. #define DEVICE_MOUSE        "/dev/input/event3"  
  11.   
  12.   
  13. int main(void)  
  14. {  
  15.     int fd = -1, ret = -1;  
  16.     struct input_event ev;  
  17.       
  18.     // 第1步:打开设备文件  
  19.     fd = open(DEVICE_KEY, O_RDONLY);  
  20.     if (fd < 0)  
  21.     {  
  22.         perror("open");  
  23.         return -1;  
  24.     }  
  25.       
  26.     while (1)  
  27.     {  
  28.         // 第2步:读取一个event事件包  
  29.         memset(&ev, 0, sizeof(struct input_event));  
  30.         ret = read(fd, &ev, sizeof(struct input_event));  
  31.         if (ret != sizeof(struct input_event))  
  32.         {  
  33.             perror("read");  
  34.             close(fd);  
  35.             return -1;  
  36.         }  
  37.           
  38.         // 第3步:解析event包,才知道发生了什么样的输入事件  
  39.         printf("%s.\n", (unsigned char *)&ev);    
  40.     }  
  41.       
  42.       
  43.     // 第4步:关闭设备  
  44.     close(fd);  
  45.       
  46.     return 0;  
  47. }  

二、input设备应用层编程实践2

1、解析键盘事件数据、鼠标事件数据

即更换设备文件,第三步换成下面代码,运行查看。

[cpp]  view plain  copy
  1. // 第3步:解析event包,才知道发生了什么样的输入事件  
  2.         printf("-------------------------\n");  
  3.         printf("type: %hd\n", ev.type);  
  4.         printf("code: %hd\n", ev.code);  
  5.         printf("value: %d\n", ev.value);  
  6.         printf("\n");  


2、事件类型分析(type)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值