A Radio Frequency Identification (RFID) system is an identification system that uses radio waves to retrieve data from a device called a tag or transponder.

RFID surrounds us in our daily lives-in supermarkets, libraries, bookstores, etc. RFID provides a quick and efficient way to collect information, such as taking stock in a warehouse, as well as tracking the whereabouts of items.

In this article, you will learn how to build a Windows application that incorporates RFID technology for data collection. I’ll demonstrate how to use two RFID readers and then I’ll compare their relative pros and cons.

A Quick Introduction to RFID

In its bare minimum, a RFID system consists of two main components:

  • Reader/Writer
  • Tags

An RFID reader/writer contains a scanning antenna and a transceiver. It uses the scanning antenna to send out radio frequency signals in a relative short range. The radio frequency sent out is used to communicate and power tags (also known as transponders) that are within range, which will then transmit the data on the tag back to the reader. The information sent out by the tag is then picked up by the scanning antenna. The data is then interpreted and decoded by the transceiver.

There are two types of RFID tags-active and passive. Active RFID tags have their own power source and hence they can transmit signals that travel farther. In contrast, passive RFID tags have no power source and they have to rely solely on the signal sent from the scanning antenna to power them. Hence the range supported by passive tags is limited. Active tags are bigger in size than passive tags and have a limited life span (until the power source runs out). Passive tags, on the other hand, are much smaller in size and have virtually unlimited life span.

There are two types of RFID tags: active and passive.

RFID systems are categorized by their transmitting frequencies and are broadly grouped into three bands: Low Frequency (LF), High Frequency (HF), and Ultra High Frequency (UFH). Table 1 shows the different frequencies used by the three bands and their characteristics.

Each RFID tag has a unique tag ID. Tags carry no more than 2KB of data and can store information such as history, location, etc.

Most common RFID applications use the tag ID transmitted by RFID tags as a key to information stored in databases. For example, an RFID tag attached to an employee passcard only contains an RFID tag ID, which an application can use to retrieve more detailed employee information stored in the organization databases. While read-only RFID applications are cheaper, there are occasions where you might need to write data back to an RFID tag, in which case you’ll use read-write tags. You might find read-write RFID systems in a subway, for example, where you may need to write back information to a tag in stored value cards. Note that some tags can only be written once.

Building Attendance Tracking Application

Now that you have a good understanding of how RFID works, I’ll show you how to build a simple attendance application that registers an employee when he reports for work. Figure 1 shows the user interface of the application.

Figure 1: The attendance system you will build in this article.

When an employee scans his employee passcard that has an embedded RFID tag, the application that receives the ID from the RFID tag will display the employee information. The application’s administrator can assign an unused tag to an employee by using the buttons on the right of the application. For security reasons, the application will clear the employee information after three seconds. To deploy this application in a real-life setting, you would hide the administrative functions so that the user only sees the necessary information (see Figure 2).

Figure 2: Hiding the administrative functions in a deployed environment.

RFID Reader #1: Parallax’s RFID Reader Module

In this example, I’ll show you how to use Parallax’s RFID Reader Module (http://www.parallax.com/detail.asp?product_id=28140). This low-cost RFID reader ($39) reads passive RFID transponder tags and uses serial communication to transmit the tag IDs. As you can see in Figure 3, the reader has four pins at the bottom (from left to right):

Figure 3: The Parallax’s RFID Reader Module.
  • VCC - +5V DC power
  • /ENABLE - Enable (Ground) or disable (+5V DC) pin
  • SOUT - Serial output
  • GND - Ground

The effective read range of Parallax’s RFID Reader module is 1¾” to 3” inches (depending on the tag used). When the Reader Module acquires a tag ID, data is sent through the serial port using a 12-byte ASCII string. The LF (Line Feed) serves as the Start byte and the CR (Carriage Return) serves as the Stop byte. The ten digits in between serve as the unique tag ID.

RFID Tags

The Parallax’s RFID Reader Module reads the following tags:

Setting Up the Reader

In order to connect the reader to your computer, you need to perform a TTL-to-RS-232 level shifting so that the data can be read via a serial port. One way would be to connect the reader to the RS-232 DCE AppMod (http://www.parallax.com/detail.asp?product_id=29120; $29).

For my project, I used the Javeline Demo Board (http://www.parallax.com/detail.asp?product_id=550-00019; $119) to connect to the reader.

Tip: Either board will work well. I just happened to have the Javeline Demo Board, which is the more expensive option. If you are a modder, you can wire up the reader yourself using an RS232 level shifting IC.

Figure 4 shows the wiring on the Javeline Demo Board. After that, you need to:

Figure 4: The wiring on the Javeline Demo Board.
  • Connect a 5V power source to the power connector
  • Connect your RS-232 serial cable to the serial port at the top of the board.
  • Connect the reader module to board using the pins shown in the diagram

Tip: Be sure to use a “straight” serial cable to connect the board to your computer, or else you will not be able to get any data from the reader.

If you do not have a serial port on your computer, you can use a USB-to-serial converter to convert a USB connector into a serial port. You will also need a DB9 straight serial cable.

Figure 5 shows the assembled reader and board.

Figure 5: The Parallax RFID Reader and the Javeline Demo Board connected and ready to go.

Building the Application User Interface

Using Visual Studio 2005, create a new Windows application and name it C:\Attendance. You will use the Northwind sample database provided by SQL Server 2000 with SQL Express. (See the sidebar, Installing the Sample Database.) To simplify data-binding, you will use the drag-and-drop data-binding feature that is new in Visual Studio 2005.

In addition, you will also add a new TagID field to the Employees table in the Northwind database. To do so:

  • Go to Server Explorer (from the View menu choose Server Explorer).
  • Right-click on Data Connections and select Add Connection….
  • Select the Microsoft SQL Server (SqlClient) data source and in the server name field, enter “.\SQLEXPRESS” (assuming you have SQL Express installed on your local computer). Select Northwind as the database name and click OK.
  • In Server Explorer, expand the Northwind database and then the Tables item. Double-click Employees and add the TagID field (Figure 6).
Figure 6: Adding a new TagID field to the Employees table.

Note: Ensure that the data source selected is “Microsoft SQL Server (SqlClient)”. If it is not, click Change… and select Microsoft SQL Server.

First, add a new data source to your project by selecting Add New Data Source from the Data menu. In the Data Source Configuration Wizard dialog box, select Database and click Next. Click the New Connection button to specify the database to use. You will see the Add Connection dialog box (Figure 7). As before, enter “.\SQLEXPRESS” as the server name and select Northwind as the database. Click OK.

Figure 7: Adding a new connection to the Northwind database.

Back in the Data Source Configuration Wizard, click Next. In the next screen, select the table and fields to use. Expand the Tables and Employees item and then check the following fields (Figure 8):

Figure 8: Choosing the fields to use in the Employees table.
  • EmployeeID
  • LastName
  • FirstName
  • Title
  • Photo
  • TagID

From the Data menu, choose Show Data Sources to view the newly added data source. Figure 9 shows the Employees data source. By default, the Employees table is bound to a DataGridView control and all its fields (except the Photo field) are bound to TextBox controls. You should change the bindings to those as shown in Table 2.

Figure 9: The Employees data source.

The Employees data source should now look like the right side of Figure 9.

Drag the Employees data source onto the default Form1. Figure 10 shows the controls that automatically populate the form. For the PictureBox control, set its Size property to “95,110” and SizeMode to “StretchImage.”

Figure 10: The data-bound controls.

Note: Move the TagID label and its accompanying Label control (on the right) to the top.

To test that the data-binding works, you can now press F5 to debug the application. Figure 11 shows the application displaying the records in the Employees table.

Figure 11: Testing to ensure that the data-binding works.

Next you’ll add controls to the form to allow an administrator to assign a RFID tag to a user. Figure 12 shows the controls to add.

Figure 12: Populating the form with the various controls.

For the txtTagID control, set both the ReadOnly and the Multiline properties to True.

In addition, drag a Timer control from the Toolbox onto the form. This control will ensure that the displayed employee record will be cleared after three seconds.

Coding the Application

With the UI of the application out of the way, you can now focus on writing the code to wire up all the controls. Switch to the code-behind of Form1 and import the following namespaces.

Imports System.Data
Imports System.Data.SqlClient
Imports System.IO

Declare the member variables and constants seen in Listing 1.

When the form loads, you first clear the displayed employee by setting its filter to a non-existent tag ID. The Timer control clears the displayed employee after a certain amount of time, and in this case you will set it to three seconds (as defined by the Interval constant). That is to say, when an employee is identified using his RFID tag, his information will be cleared from the screen after three seconds.

As the Parallax’s RFID Reader Module uses a serial connection, you will use the SerialPort class to communicate with the reader.

Note: For this example, I have assumed that you’ll connect the COM3 port to the RFID Reader Module. You need to change it to the correct port number for your own use.

Listing 2 shows the code for the Form1_Load event.

To receive incoming data from the SerialPort class, you need to service the DataReceived event. In this case, when incoming data is received, you will update the txtTagID control. Listing 3 shows the code for the DataReceived event.

You need to define a delegate to call a routine to update the txtTagID control. Here, define the myDelegate() delegate and the updateTextBox() subroutine.

'--- update the Tag ID textbox    
Public Delegate Sub myDelegate()
Public Sub updateTextBox()
    ' for receiving plain ASCII text
    With txtTagID
       .AppendText( _
          serialPort.ReadExisting)
       .ScrollToCaret()
    End With
End Sub    

One important point you need to understand about RFID readers (at least for the two RFID readers shown in this article) is that when a tag is scanned, it will continuously send the tag ID to the serial connection. For example, suppose a tag with ID of 0F0296AF3C is placed near the reader. In this case, the reader will continuously send the value of 0F0296AF3C to the serial connection. For the Parallax’s reader, each value starts with the line feed character (character 10 - <10>) and ends with a carriage return character (character 13 - <13>). To make matters complicated, using the ReadExisting() method of the SerialPort class does not guarantee that you will read the complete tag ID in its entirety. This is because a value may be sent in four blocks, like this:

<10>0F
029
6AF3
C<13>

You may be tempted to use the ReadLine() method of the SerialPort class to read incoming data, but that will not work as the ReadLine() method will look for <13><10> at the end of the line. But since the incoming data does not end with <10>, this will cause the application to go into an infinite loop.

In addition, if you don’t clear the incoming data buffer fast enough, you may get a series of data queued up like this:

<10>
0F
029
6AF3
C
<13>
<10>
04
158D
C82B
<13>

Instead of writing elaborate logic to process the incoming data, an easy way is to append all incoming data to a TextBox control (with the Multiline property set to True). Using the data just described, Figure 13 shows what the TextBox control will look like.

Figure 13: Appending incoming data to a TextBox control.

The second to the last line will hence always contain the Tag ID that you are interested in if the last line is an empty string. In contrast, if the tag ID is only partially received, the state of the TextBox control would be as shown in Figure 14.

Figure 14: The state of the TextBox control containing the last incomplete tag ID.

As all incoming data is updated in the TextBox control, you can check if the tag ID belongs to an employee whenever there are changes in the content of the TextBox control. You’ll use the TextChanged event (Listing 4) to detect the change.

The TextChanged event first examines if the last line in the txtTagID control is an empty string; if it is, then the scanned tag ID can be found in the second to last line. Using this tag ID, the code checks the time difference between the current time and the last time the tag ID was read. If it is less than three seconds and the tag ID is the same as the last read tag ID, it means that it is the same user and the current tag ID should be ignored. Using this implementation, the same user would be ignored for the next three seconds from the moment he first scanned his tag.

With the tag ID, you will apply a filter to the EmployeesBindingSource control to look for an employee with a matching tag ID. If an employee is found, an entry will be written to the log file using the WriteToLog() subroutine.

Private Sub WriteToLog( _
   ByVal employeeID As String, _
   ByVal employeeName As String)
    '--- write to log file 
    Dim str As String = employeeID & _
       "," & employeeName & "," & _
       Now & Chr(13)
    My.Computer.FileSystem. _
       WriteAllText(FILE_NAME, str, _
       True)
End Sub    

Figure 15 shows the content of a typical log file.

Figure 15: The content of a typical log file.

The Timer control will fire the Tick event every three seconds (as determined by the value set in its Interval property). Hence you need to service the Tick event so that every time it fires, you can clear the current employee information that is displayed. Here is the implementation of the Tick event.

Private Sub Timer1_Tick( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles Timer1.Tick
    '--- clear the employee 
    EmployeesBindingSource.Filter = _
       "TAGID='xxxxxxxxxx'"
    Timer1.Enabled = False
End Sub    

If the tag ID that was just scanned in does not belong to any user, the administrator can assign the tag ID to an employee. To do so, he can first click the Find button to find the user and then assign the tag ID to that user. Here is the implementation of the Find button.

Private Sub btnFind_Click( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles btnFind.Click
    '--- search for employee 
    If txtEmployeeID.Text = _
       String.Empty Then
       EmployeesBindingSource. _
          RemoveFilter()
    Else
       EmployeesBindingSource. _
          Filter = _
          "EmployeeID='" & _
          txtEmployeeID.Text & "'"
    End If
End Sub    

Basically, you search for a user by applying a filter to the EmployeesBindingSource control. To assign a tag ID to the current employee, copy the tag ID onto the TagIDLabel1 control and then save the changes. Listing 5 shows the implementation of the Assign tag to Employee button.

The Deassign Tag From Employee button allows a tag ID to be disassociated from an employee. This is easily accomplished by setting the TagIDLabel1 control to an empty string. Listing 6 shows the implementation of the Deassign Tag From Employee button.

Testing the Application

You are now ready to test the application. Press F5 to debug the application. Take a tag and scan it using the RFID reader. The application should register your tag ID and shows that no employee is found (Figure 16).

Figure 16: Scanning a tag that does not belong to any employee.

You can associate the tag ID with an employee by searching for an employee (enter the employee ID in the Textbox and click the Find button or leave it empty and it will return all records). Once you have located the employee you want, click the Assign Tag to Employee button to assign the tag ID to the employee.

The next time you scan the same tag, the application will show the employee.

RFID Reader #2: PhidgetRFID

The second RFID reader I will show you how to use is the PhidgetRFID reader (http://www.phidgetsusa.com/cat/viewproduct.asp?category=3000&;subcategory=3100&SKU=1023; $59.95); see Figure 17) from Phidgets Inc. The PhidgetRFID is also a read-only RFID reader than can read tags within a four-inch proximity.

Figure 17: The PhidgetRFID.

Unlike the Parallax’s RFID Reader Module, the PhidgetRFID uses a USB connection, which is actually easier for most people since almost all computers today support USB devices. And since it draws power from the USB connection, you don’t need to provide an external power source. Simply connect the PhidgetRFID to your computer and start scanning.

RFID Tags

Instead of purchasing the standalone PhidgetRFID reader, I suggest you purchase the PhidgetRFID kit (http://www.phidgetsusa.com/cat/viewproduct.asp?category=3000&;subcategory=3300&SKU=93001; $79.25), which comes with the following:

  • 6 30mm disc RFID tags
  • 2 credit card-sized RFID tags
  • 2 Keyfob RFID tags
  • USB cable

The PhidgetRFID reads RFID tags that use the EM Marrin protocol, EM4102 (this is a 125kHz read-only protocol).

Tip: The PhidgetRFID also reads the tag I used for the Parallax RFID Reader Module. In fact, the tags described here also works with Parallax’s reader.

Building the Sample Application

Rather than modify the application built in the previous section to work with the PhidgetRFID reader (and have a lot of repeating code snippets), I have opted to build a simpler application so that you can learn the fundamentals without being bogged down with the details of the application.

Using Visual Studio 2005, create a new Windows application and populate the default form with the controls as shown in Figure 18.

Figure 18: Populating the form with the controls.

Using this application, you can view the tag ID that is being scanned and you can also programmatically turn on/off the LED on the reader itself and enable/disable the reader.

Running the PhidgetRFID Web Service

Phidget has made it easy for .NET programmers to use the PhidgetRFID reader. Developers can control the reader by the PhidgetWebService, a component that interacts with your PhidgetRFID reader. You must install and run the PhidgetWebService on the computer that has the PhidegetRFID connected. Once the PhidgetWebService is up and running, your program can then communicate with it in order to control the PhidgetRFID reader. You can obtain the Phidget library (containing the PhidgetWebService) from http://www.phidgetsusa.com (go to Downloads then choose Release) and download the PHIDGET.msi file.

Note: Phidget’s use of the term “WebService” is a little misleading here. PhidgetWebService is not an XML Web service that most developers are familiar with. Rather, it is a Windows Service that runs in the background.

Once installed, you can find the PhidgetWebService in the C:\Program Files\Phidgets directory. You can invoke the PhidgetWebService Manager (a GUI version of the WebService) by running the PhidgetWebServiceManger.exe from this directory. Once it is up and running, you’ll find it in the System Tray (Figure 19).

Figure 19: The PhidgetWebService Manager in the System Tray.

Double-click on the icon to launch the PhidgetWebService Manager. Using the manager, you can change the settings of the WebService as well as manage your Phidget devices (not just the PhidgetRFID reader). As shown in Figure 20, the PhidgetWebService is listening at port 5001 and requires a password “pass” (the default) in order to access it. With your PhidegetRFID reader attached to your computer, click Start. In my case, my reader has the serial number of 6207, which can be used to uniquely identify it.

Figure 20: The PhidgetWebService Manager.

One unique feature of the PhidgetWebService is that your client application need not necessarily be running on the same computer as the one with the reader connected. The client application uses sockets communication to talk to the PhidgetWebService, so this means that you can connect the PhidgetRFID reader to one computer and you can run the client application on another computer (as long as they can see each other on the network). Figure 21 shows one possible scenario. The advantage of this approach is that your client can be running on mobile platform devices (such as Pocket PC) as long as it can communicate with the host computer using sockets communications.

Figure 21: The client and the reader need not be on the same computer.

PhidgetRFID APIs

The PhidgetRFID reader, which is installed when you install the PhidgetWebService, exposes its functionality as APIs located in the PhidgetNET.dll library.

To use the PhidgetRFID, first import the PhidgetNET.dll library into your application. Right-click on the project name in Solution Explorer and then select Add Reference…. In the Browse tab, navigate to C:\Program Files\Phidgets\ and select PhidgetNET.dll.

Coding the Application

Switch to the code-behind of Form1 and first declare a member variable representing the PhidgetRFID reader:

Public Class Form1
    Dim WithEvents RFIDReader As _
       PhidgetsNET.PhidgetRFID

When the form is loaded, instantiate the PhidgetReader variable and open a connection to the computer running the PhidgetWebService. This is accomplished in the Form1_Load event:

Private Sub Form1_Load( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles MyBase.Load
    RFIDReader = New _
       PhidgetsNET.PhidgetRFID
    RFIDReader.OpenRemoteIP( _
       "localhost", 5001, -1, "pass")
    ToolStripStatusLabel1.Text = _
       "Not Connected"
End Sub    

Note: Notice that I used localhost as my reader connected to my local computer. 5001 corresponds to the port number entered in the PhidgetWebService Manager (Figure 20). The -1 refers to the first device that is found in the PhidgetWebService. Alternatively, you can use 6207 (the device serial number). The “pass” is the password (also set in the PhidgetWebService Manager) needed.

For the PhidgetRFID, you need to service four important events:

  • Attach. Fired when a PhidgetRFID reader is attached to the computer running the PhidgetWebService.
  • Detach. Fired when a PhidgetRFID reader is detached from the computer running the PhidgetWebService.
  • Error. Fired when there is an error with the PhidgetRFID reader.
  • Tag. Fired when a tag is scanned using the PhidgetRFID reader.

In the Attach event, when a reader is connected, you will turn on the LED on the reader as well as enable the reader by using the SetOutputState() method of the PhidgetRFID class:

Private Sub RFIDReader_Attach( _
   ByVal sender As Object, _
   ByVal e As _
      PhidgetsNET.AttachEventArgs) _
   Handles RFIDReader.Attach
    '--- display the status
    ToolStripStatusLabel1.Text = _
       "Phidget RFID Reader Connected"
    '--- Enable onboard LED
    chkTurnOnLED.Checked = True
    RFIDReader.SetOutputState(2, True)
    '--- Enable RFID Reader 
    chkEnableReader.Checked = True
    RFIDReader.SetOutputState(3, True)
End Sub    

When you detach the reader, you simply update its status in the status bar.

Private Sub RFIDReader_Detach( _
   ByVal sender As Object, _
   ByVal e As _
      PhidgetsNET.DetachEventArgs) _
   Handles RFIDReader.Detach
    '--- display the status 
    ToolStripStatusLabel1.Text = _
   "Phidget RFID Reader Not Connected"
End Sub    

The same goes for the Error event.

Private Sub RFIDReader_Error( _
   ByVal sender As Object, _
   ByVal e As _
      PhidgetsNET.ErrorEventArgs) _
   Handles RFIDReader.Error
    '--- display the error 
    ToolStripStatusLabel1.Text = _
    e.getError
End Sub    

For the Tag event, you will invoke a delegate to display the tag ID.

Private Sub RFIDReader_Tag( _
   ByVal sender As Object, _
   ByVal e As _
      PhidgetsNET.TagEventArgs) _
   Handles RFIDReader.Tag
   '--- when incoming data is 
   '--- received, update the 
   '--- TagID textbox 
    txtTagID.BeginInvoke(New _
       myDelegate( _
       AddressOf updateTextBox), _
       New Object() {e.getTag})
End Sub    

The delegate and the subroutine to update the textbox with the tag ID is defined as follows:

'--- update the Tag ID textbox     
Public Delegate Sub myDelegate( _
   ByVal str As String)
    
Public Sub updateTextBox( _
   ByVal str As String)
    '--- update the textbox control 
    With txtTagID
        .Text = str
    End With
End Sub    

You can also turn on/off the LED on the reader during run time. This is serviced by the CheckChanged event of the chkTurnOnLED control.

Private Sub _    
   chkTurnOnLED_CheckedChanged( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles chkTurnOnLED.CheckedChanged
    '--- Enable/Disable onboard LED 
    RFIDReader.SetOutputState(2, _
       chkTurnOnLED.Checked)
End Sub    

Similarly, you can enable/disable the reader by servicing the CheckChanged event of the chkEnableReader control.

Private Sub _
   chkEnableReader_CheckedChanged( _
   ByVal sender As System.Object, _
   ByVal e As System.EventArgs) _
   Handles _
      chkEnableReader.CheckedChanged
    '--- Enable RFID Reader 
    RFIDReader.SetOutputState(3, _
       chkEnableReader.Checked)
End Sub    

Testing the Application

That’s it! You can now press F5 to test the application. Ensure you’ve used PhidgetWebService Manager to enable your PhidgetRFID reader. Figure 22 shows a tag scanned successfully.

Figure 22: A tag scanned successfully.

Comparing the Two RFID Readers

You have seen the two types of RFID readers and so which one should you go for? Here are some factors you can consider.

Cost

In terms of cost, the Parallax RFID reader is very affordable at $39. However, you need to factor in the additional cost of wiring up the unit. You need to buy a power adapter (output 5V DC), a serial cable, as well as the additional hardware needed to convert the signal to serial output. In contrast, the PhidgetRFID kit costs about $58 and includes everything you need.

Ease of Use

In terms of use, the PhidgetRFID is truly plug and play. Just make sure you download the PhidgetWebService and you can start coding straight away. The Parallax RFID Reader Module takes some effort to set up, especially if you are not familiar with electronics and worry about causing damage to the unit.

Flexibility

If you simply want to connect an RFID reader to your computer, then the PhidgetRFID is clearly an easy option. However, the beauty of the Parallax RFID Reader Module is that it allows you to connect the unit to devices other than a PC, such as an embedded controller. Using the Parallax RFID Reader Module, you can embed it in a door and write your own code to authenticate users.

Tip: While at the moment, you can’t really use the .NET Framework (or the .NET Compact Framework) to write code for an embedded controller, I am really looking forward to the new .NET Micro Framework (http://www.aboutnetmf.com/entry.asp) to allow me to do the job in the near future.

Dimension

Both readers are similar in size, and are flat enough to be hidden from view.

Summary

In this article, you have seen how RFID works and then learned to build a Windows application that uses two RFID readers-one from Parallax and one from Phidget. Depending on your needs, both low-cost readers offer a lot of exciting possibilities for integrating RFID capabilities into your projects. If you have not tried RFID yet, this is a good time to begin!

*Source: http://www.atmel.com/dyn/resources/Prod_documents/secrerf_3_04.pdf