我有一個仿真鍵盤的USB RFID讀卡器。 所以當我把一張卡片放到它上面時,我在終端窗口上看到字符串-i.e. "0684a24bc1"
從/ dev/input讀取
但我想在我的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;
}
你不應該設置'O_NONBLOCK'標誌使描述符無阻塞嗎? – 2013-04-11 12:50:15
此外,直接從設備讀取數據時,您會讀取_raw_數據,然後將其轉換爲可以像終端一樣讀取的字符。 – 2013-04-11 12:52:51
我只想補充一點,這是一個糟糕的RF-ID驅動程序實現。它應該作爲一個字符設備來實現。 – stdcall 2013-04-11 13:31:21