linux 读取键盘值
·
#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);
}
魔乐社区(Modelers.cn) 是一个中立、公益的人工智能社区,提供人工智能工具、模型、数据的托管、展示与应用协同服务,为人工智能开发及爱好者搭建开放的学习交流平台。社区通过理事会方式运作,由全产业链共同建设、共同运营、共同享有,推动国产AI生态繁荣发展。
更多推荐


所有评论(0)