该程序可运行在电脑ubuntu系统和嵌入式linux平台中。直接上代码:
#include <stdio.h>
#include <linux/fb.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <sys/ioctl.h>
#include <string.h>
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <poll.h>
#include <linux/input.h>
#include <stdio.h>
#include <stdlib.h>
#include <dirent.h>
#include <sys/time.h>
#include <string.h>
#include <unistd.h>
#ifdef __cplusplus
#if __cplusplus
extern "C" {
#endif
#endif
int main()
{
/*打开触摸屏设备*/
int fd=open("/dev/input/event4",2);
if(fd<0)
{
printf("触摸屏驱动打开失败\n");
return 0;
}
struct pollfd fds=
{
.fd=fd,
.events=POLLIN,
};
/*
struct input_event {
struct timeval time;
__u16 type;
__u16 code;
__s32 value;
};
*/
struct input_event touchxy;
while(1)
{
poll(&fds,1,-1);
read(fd,&touchxy,sizeof(touchxy));
switch(touchxy.type)
{
case EV_KEY://按键值
printf("key=%d\tstat=%d\n",touchxy.code,touchxy.value);
break;
case EV_ABS://绝对坐标
if(touchxy.code == ABS_X)//x坐标
{
printf("x=%d\n",touchxy.value);
}
else if(touchxy.code == ABS_Y)//Y坐标
{
printf("y=%d\n",touchxy.value);
}
else if(touchxy.code == ABS_PRESSURE)//压力值
{
printf("press=%d\n",touchxy.value);
}
break;
}
}
return 0;
}
#ifdef __cplusplus
#if __cplusplus
}
#endif
#endif
比如我在ubuntu运行测试笔记本上的触摸板,先用命令cat /proc/bus/input/devices查看触摸板是哪个event:
从图中可以看到是event4,所以我们在open的时候要open event4
然后把代码保存为tp_test-ubuntu-touchpad.c。
在ubuntu里用命令编译:gcc tp_test-ubuntu-touchpad.c -o tp_test-ubuntu-touchpad。
然后运行:sudo ./tp_test-ubuntu-touchpad。这时去触摸,即可看到数据打印。
$ sudo ./tp_test-ubuntu-touchpad
key=330 stat=1
x=4151
y=3918
press=76
key=325 stat=1
press=74
press=69
press=63
press=52
key=330 stat=0
press=0
key=325 stat=0
结束!