gpt4 book ai didi

c - 从/dev/input读取

转载 作者:IT王子 更新时间:2023-10-29 00:52:57 25 4
gpt4 key购买 nike

我有一个模拟键盘的 USB RFID 读卡器。因此,当我将卡片放入其中时,我会在终端窗口中看到字符串 - 即“0684a24bc1”

但我想在我的 C 程序中阅读它。当我使用时没有问题:scanf("%s",buff);

但是当我使用下面的代码时,我得到了很多(大约 500 字节)无法识别的数据。为什么?我想要非阻塞读取。

#include <stdio.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>
#include <termios.h>

int main(int argc, char ** argv) {
int fd;
char buf[256];

fd = open("/dev/input/event3", O_RDWR | O_NOCTTY | O_NDELAY);
if (fd == -1) {
perror("open_port: Unable to open /dev/ttyAMA0 - ");
return(-1);
}

// Turn off blocking for reads, use (fd, F_SETFL, FNDELAY) if you want that
fcntl(fd, F_SETFL, 0);


}

while(1){
n = read(fd, (void*)buf, 255);
if (n < 0) {
perror("Read failed - ");
return -1;
} else if (n == 0) printf("No data on port\n");
else {
buf[n] = '\0';
printf("%i bytes read : %s", n, buf);
}
sleep(1);
printf("i'm still doing something");

}
close(fd);
return 0;
}

最佳答案

根据Linux input documentation , section 5,/dev/input/eventX 设备返回数据如下:

You can use blocking and nonblocking reads, also select() on the /dev/input/eventX devices, and you'll always get a whole number of input events on a read. Their layout is:

struct input_event {
struct timeval time;
unsigned short type;
unsigned short code;
unsigned int value; };

'time' is the timestamp, it returns the time at which the event happened. Type is for example EV_REL for relative moment, EV_KEY for a keypress or release. More types are defined in include/linux/input.h.

'code' is event code, for example REL_X or KEY_BACKSPACE, again a complete list is in include/linux/input.h.

'value' is the value the event carries. Either a relative change for EV_REL, absolute new value for EV_ABS (joysticks ...), or 0 for EV_KEY for release, 1 for keypress and 2 for autorepeat.

关于c - 从/dev/input读取,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15949163/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com