Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read from /dev/input

Tags:

c

linux

I have an USB RFID card reader which emulates keyboard. So when i put an card to it i see the string on a terminal window -i.e. "0684a24bc1"

But i would like to read it in my C program. There is no problem when i use: scanf("%s",buff);

But when i use below code i got a lot (about 500 bytes) not recognized data. Why? I would like to have non blocking read.

#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;
}
like image 291
szymon hrapkowicz Avatar asked Apr 11 '13 12:04

szymon hrapkowicz


1 Answers

According to the Linux input documentation, section 5, the /dev/input/eventX devices return data as following:

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.

like image 117
Hasturkun Avatar answered Sep 20 '22 15:09

Hasturkun