driver:
#include <linux/input.h>
#include <linux/gpio.h>
static struct input_dev *test_input = NULL;
test_input = input_allocate_device();
if(!test_input)
{
input_free_device(test_input);
pr_err("input device allocate fail\n");
return -1;
}
test_input->evbit[BIT_WORD(EV_KEY)] |= BIT_MASK(EV_KEY);
test_input->keybit[BIT_WORD(KEY_UP)] |= BIT_MASK(KEY_UP);
test_input->name = "test_input";
status = input_register_device(test_input);
pr_info("register test event start\n");
if(status)
{
pr_err("Fail to register test_input:%d\n", status);
goto err_input_dev;
}
err_input_dev:
input_unregister_device(test_input);
input_free_device(test_input);
//report event to user space
input_report_key(test_input, KEY_DOWN, flag);
input_sync(test_input);
user space:
int ret, input_fd = -1;
struct input_event package;
int fd;
fd = open(/dev/input/event4, O_RDWR);
if(fd < 0)
{
perror("open input device error");
exit(1);
}
while(1)
{
bzero(&package,sizeof(package));
ret = read(fd, &package,sizeof(package));
//printf("b1:0x%x 0x%x 0x%x,0x%x\n", package.type, package.code, package.value, ret);
if(ret < 0)
{
perror("read");
exit(1);
}
if(package.type == EV_KEY)
{
if(package.code == KEY_UP)
{
// printf("c1:0x%x 0x%x 0x%x\n", package.type, package.code, package.value);
printf("here is the callback\n");//callback
}
}
}
这里顺便介绍一下如何获取input子系统对应的event事件节点对应名称:
查看命令cat /proc/bus/input/devices ,其中Name即为事件对应名称,如下:
I: Bus=0019 Vendor=0001 Product=0001 Version=0100
N: Name="gpio-keys"
P: Phys=gpio-keys/input0
S: Sysfs=/devices/platform/gpio-keys/input/input2
U: Uniq=
H: Handlers=kbd event2
B: PROP=0
B: EV=3
B: KEY=40000000000000 0 0 0
那如何通过代码获取事件名称呢,比如/dev/input/eventXX下有多个event设备节点的时候,我们怎么准确找到自己想要监听的设备,处理方法可如下:
通过ioctl命令EVIOCGNAME,能获取dev/input/event*对应的Device Name,EVIOCGNAME:Get Device Name.
char input_name[256] = {'\0'};
int find_input_by_name(void)
{
char name[64];
int fd = 0;
int i;
for (i = 0; i < 32; i++) {
sprintf(name, "/dev/input/event%d", i);
if ((fd = open(name, O_RDONLY)) >= 0) {
ioctl(fd, EVIOCGNAME(sizeof(input_name)), input_name);
if (!strcmp(input_name, "mcu_gpio_req"))
{
printf("find input_event success:%s\n", name);
strcpy(input_name, name);
printf("find input_event success inputname :%s\n", input_name);
close(fd);
break;
}
close(fd);
}
}
printf("i is %d\n", i);
if(i == 32)
{
printf("input name not exist\n");
return -1;
}
printf("find input_event success:%s\n", name);
return 0;
}