Monday, November 25, 2013

C Code to Read RFID Data from an Innovations ID-20LA Using the SparkfunRFID USB Reader Board

This example shows a C program that reads RFID data from an Innovations 20-LA reader using the Sparkfun RFID USB reader board.  This RFID reader board makes it easy to connect the Innovations 20-LA to the Raspberry Pi using a USB cable.

This code is based on sample serial port code by Gary Frerking that I found at the Linux Documentation Project.

This very basic program reads an RFID card and prints the card's unique number to the terminal window.  The program runs continuously until interrupted by the user (ctrl-c).

C Code

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <termios.h>
#include <stdio.h>
#include <string.h>
#include <stdlib.h>

#define BAUDRATE B9600
#define MODEMDEVICE "/dev/ttyUSB0"
#define TRUE 1

        int fd, c, res;
        struct termios newtio;
        char buf[13];
        fd = open(MODEMDEVICE, O_RDWR | O_NOCTTY );
        if (fd < 0) { perror(MODEMDEVICE); exit(-1); }
        bzero(&newtio, sizeof(newtio)); /* clear struct for new port settings */
        /* BAUDRATE: Set bps rate. You could also use cfsetispeed and cfsetospeed.
           CRTSCTS : output hardware flow control (only used if the cable has
                     all necessary lines. See sect. 7 of Serial-HOWTO)
           CS8     : 8n1 (8bit,no parity,1 stopbit)
           CLOCAL  : local connection, no modem contol
           CREAD   : enable receiving characters */
        newtio.c_cflag = BAUDRATE | CRTSCTS | CS8 | CLOCAL | CREAD;
        /* IGNPAR  : ignore bytes with parity errors
                     otherwise make device raw (no other input processing) */
        newtio.c_iflag = IGNPAR;

        /*  Raw output  */
        newtio.c_oflag = 0;

        /* ICANON  : enable canonical input
                     disable all echo functionality, and don't send signals to calling
                     program */
        newtio.c_lflag = ICANON;
        /* now clean the modem line and activate the settings for the port */
        tcflush(fd, TCIFLUSH);
        while (TRUE) { /* loop continuously */
                res = read(fd, buf, 13);
                buf[res] = 0;
                printf("%s", buf, res);

1 comment: