#include <stdio.h>
#include <linux/input.h>
#include <fcntl.h>
#include <unistd.h>
#include <string.h>
char *GetKeyboardEventNum(char *kybName)
{
char *p;
char name[64]; /* RATS: Use ok, but could be better */
char buf[256] = {
0,
}; /* RATS: Use ok */
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)) >= 0)
{
ioctl(fd, EVIOCGNAME(sizeof(buf)), buf);
if (strstr(buf, kybName))
{
close(fd);
p = name;
return p;
}
close(fd);
}
}
return "";
}
typedef void (*func)(int); //定义函数类型
extern void GetKeyBoard(func callback);
void GetKeyBoard(func callback)
{
int keys_fd; //文件标志
char ret[2];
struct input_event t; //读取到的input设备数据是一个结构体
char *DEV_PATH = GetKeyboardEventNum("SIGMACHIP USB Keyboard");
keys_fd = open(DEV_PATH, O_RDONLY); //权限不通过的时候一般会返回-1
if (keys_fd <= 0)
{
// printf("open /dev/input/event2 device error!\n");
return -1;
}
while (1)
{
if (
read(keys_fd, &t, sizeof(t)) == sizeof(t)) /*keys_fd指向打开的设备文件,read将从设备文件传送sizeof(t)个字节的数据到&t这个内存地址。函数执行顺利的话返回值是实际读取的字节数*/
{
if (t.type == EV_KEY)
{
if (t.value == 1)
{
printf("key %d\n", t.code); // t.code值所对应的按键在/usr/include/linux/input-event-codes.h可以查到
callback(t.code);
//printf("key %d %s\n", t.code, (t.value) ? "Pressed" : "Released"); // t.code值所对应的按键在/usr/include/linux/input-event-codes.h可以查到
}
}
}
}
close(keys_fd);
}
linux 读取键盘值
最新推荐文章于 2024-04-24 00:11:58 发布