Microsoft & .NET.NETRFID Programming: Easy Guide for Beginners

RFID Programming: Easy Guide for Beginners content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Radio Frequency Identification Device (RFID) has been getting a ton of coverage in the press ever since Wal-mart stated that they were going to require their suppliers to tag products. Over the past few years, the ability to use RFID has gotten not only cheaper, but also easier to use. By the end of this article, you’ll see just how easy it has gotten to implement a passive RFID system that hooks into your applications. I use C# and .NET in my example, but you could also use Java or several other languages to do the same thing.

The RFID Hardware

RFID generally involves a reader and a set of tags. The reader scans a tag and pulls information from it. This information can be used to uniquely identify the tag and thus identify whatever is associated to the given tag.

There are a variety of readers that can be used. These range from readers for passive tags to readers for active (non-passive) tags.

Active tags have a power source within them, such as a small battery. As such, they actually transmit can their information a much farther distance than the passive tags. A good example of the use of active tags is in cards used to pay highway toll fees as you drive by.

Passive tags are cheaper and thus are more likely what people are looking to use for solutions such as inventory, ID cards, and other forms of monitoring. Passive tags also come in a variety of shapes and sizes that make them usable in a large number of applications. These can range from small stickers that can be stuck to products, to small glass vials that can be used to track liquids. There are even key chains, credit cards, watch bands, and other forms of passive tags. Figure 1 shows some of the passive tags that I’ve obtained.

Figure 1: A variety of passive RFID tags

The cost of RFID tags can vary depending on where you buy them and how many you purchase. Most of the tags in Figure 1 cost me between $1.20 and $3, but I purchased them individually. If you buy them in large quantities, the cost will obviously drop quickly. You can find these tags and other ones from a variety of sources. I obtained these from Trossen Robotics(Click here for a list of their tags).

In addition to passive versus active, you also have to know the radio wave range of the reader and tags you are using. The tags in Figure 1 are all passive tags that operate at the 125 KHz frequency. As such, they use a reader that can recognize this frequency. I used an RFID reader from Trossen Robotics. Figure 2 shows the small PhidgetsRFID passive tag reader.

Figure 2: The Phidgets RFID reader

This particular reader plugs into a USB port and will read passive tags that operate at 125khz. You can find this reader retails for about $65 US from either Phidgets or PhidgetsUSA.

Programming RFID

Each RFID tag contains a unique ID and possibly other information. As mentioned with the readers, there are passive tags and active tags. A passive tag generally contains an antenna—actually a coil of wire—that when put near a reader creates a small charge that is enough to cause the tag to transmit its unique ID. This small charge, however, is minuscule, so a passive tag generally has to be within a couple of inches of a reader to work.

The unique tag ID is the key to using RFID in a program. The unique ID what sets one tag apart from all other tags. If you are tracking inventory, you can place a tag on an item and then associate the ID of the tag to that item. You’ve then given each item a unique key to access it by.

As an example, a credit card tag can be used as a membership card. Within your membership database, you simply need to add an additional field for the Tag ID. Before giving the card to the member, you can scan the card and associate the Tag ID to that member in your membership database. From that point forward, that unique RFID card will be associated to that member in your database. If you scan that card, you can use the retrieved unique tag ID to then search your membership database for the RFID tag number and then get the associated membership information.

This example should not sound too far off. If you have a “swipe card” that you use to access an office building, it is most likely that you are already using RFID in a manner similar to what I just described for a membership database.

RFID in Action

To repeat the key point, using RFID is simply a matter of reading the associated tag to get the unique ID. Once you have the unique ID, it is simple data. You need a reader to do the reading and tags to read. In the rest of this article, I’ll walk through what it takes to use the Phidgets RFID reader mentioned above to read standard 125 KHz tags.

The RFID Hardware

The Phidgets RFID reader simply plugs into a USB port. Once plugged in, the hardware side of the example is set up. It can’t get easier than that.

Reading a tag, however, does require a few more steps. For you to be able to tap into the hardware, you will need to install the Phidgets application programming interface (API). You can download this code from here. You also can download example programs and documentation from the site as well. While I’m using .NET on a Microsoft Windows XP machine, you will also find that there are APIs for Linux, the Mac, and other platforms as well.

Install the API by running the Phidgets21.msi file. This will install a dynamic link library that you will then be able to reference from your application. I used the 2.1 beta version of the library. If you use a different version, my code may not work because the libraries are not backward compatible. This version, however, seemed much easier to use than prior versions.

The RFID Program

Once you have the library installed, you are ready to begin building an RFID application. I’ll be using Visual Studio 2005 and C# to build the application shown in Figure 3.

Figure 3: A simple RFID application

This application simply reads tags and displays their unique IDs in the form. If you read a tag, it will be shown in the Tag text field while it is being read, and then added to the listbox once the read is complete. In this way, the listbox will maintain a history of what has been read. Figure 4 shows the dialog after the reader has been turned on (by checking the box in the form) and after a few tags have been read.

Figure 4: Having read a few tags

To build this application, you start by creating a new C# Windows Application in Visual Studio 2005. You then should add a reference to the Phidgets API you installed earlier.

Add a reference by going to the Project menu and selecting Add Reference. Choose the COM tag and search for Phidgets Library 2.1. If it isn’t there, use the Browse option and locate the DLL on you system. It is most likely to be at C:Program FilesPhidgetsPhidgetsCOM.dll. Once you’ve added this reference, you are ready to begin building the form.

The form in Figure 3 contains the following controls:

        Type         Name         Text
Checkbox cboxAntenna Turn Reader On
Label label1 TAG:
Textbox txtTag
Listbox lblPrevRFIDTags
Label lblAttached Not Attached
Label lblSerial Serial:
Label lblVersion Version:

Most of the other property values for the controls are left at the defaults. You can modify these in any way you want. I’ve included the full source code for this application in the download at the end of this article, so if you have trouble creating the form, just pull it from there.

Within the form class, which I called RFIDReader, I also set up three additional fields:

RFID   rfid1;string lastRFIDTag;Int32  TagCtr;

RFID creates an RFID object called rfid1. This object will be assigned to the RFID reader so that we can pull information from it. The lastRFIDTag string field simply stores the unique ID from the last tag read. Finally, TagCtr is used to store a simple count of the number of tags read. As you could see in Figure 4, this counter is used to display the count on the listbox. After setting up these variables, the lastRFIDTag is set to blanks and the TagCtr should be set to 0 when you first initialize your form variables.

With a form set up and variables declared, you should do one more thing before getting to the fun code. Add a couple of references to the Phidgets namespaces to the top of your listing:

using Phidgets;using Phidgets.Events;

Now the fun code begins. To use the RFID reader, you will need to create an RFID object and then open the reader. You also will want to create a few event handlers to control actions that occur from the reader. This can all be done in the Form_Load event with the following code:

private void Form1_Load(object sender, EventArgs e){   rfid1 = new RFID();   rfid1.Attach += new AttachEventHandler(rfid_Attach);   rfid1.Detach += new DetachEventHandler(rfid_Detach);   rfid1.RFIDTag += new TagEventHandler(rfid_Tag);   rfid1.RFIDTagLost += new TagEventHandler(rfid_TagLost);;}

In this code, the first thing that happens is that an RFID object is created called rfid1. This will be used to attach to the RFID hardware. Before opening the hardware for use, event handlers are created for attaching to the RFID reader (rfid_Attach), detaching from the reader (rfid_Detach), having a tag put near the reader (rfid_Tag), and having a tag move out of the reader’s range (rfid_TagLost). After adding these handlers to the rfid1 object, the open method is called to begin using the RFID object.

To use the RFID reader, in addition to being connected to your machine, it also has to be turned on. The cboxAntenna checkbox in the form shown in Figure 3 is to let you control turning the reader on and off. By checking the box, you will execute the event to turn on the reader. The code to accomplish follows:

private void antennaCheckBox_CheckedChanged(object sender,                                            EventArgs e){   rfid1.Antenna = cboxAntenna.Checked;}

As you can see, turning on the reader is simply a matter of setting the Antenna property of your RFID object to true. The value returned from cboxAntenna.Checked will either be true or false, so this will set the rfid1 Antenna property to true or false (on or off). Once it is on, you are ready to begin reading tags.

With the reader attached and turned on, the next important thing is to read a tag. This is done in the rfid_Tag event handler that was added to the rfid1 object in the Form_Load event. The code for this event hander follows:

void rfid_Tag(object sender, TagEventArgs e){   txtTag.Text = e.Tag;   lastRFIDTag = txtTag.Text;   rfid1.LED   = true;    // light on}

The tag’s unique ID will be passed into the event handler in the TagEventArgs. As you can see, the tag ID comes out of e.Tag and is simply displayed in the txtTag text box by assigning it to the text property. Because this application is only displaying the tag ID, not much is happening here.

The second line of code within this event sets the lastRFIDTag field to the ID of the tag just read. This field will be used to update the listbox on the form with the Tag ID that was just read. This update, however, won’t happen until the tag is moved off the reader. If you did the update here within the rfid_Tag event, the update could happen over and over as long as the tag remained near the reader. That is not the desired affect wanted—I only want to list the read tag once for each time it moves over and away from the reader.

The last line of code sets the LED property of the RFID reader to true. The Phidgets RFID reader has an LED light on it. By setting this property to true, the light will be turned on whenever the reader is reading a tag.

A tag may be read over and over as long as it is over the Reader. Once it is moved out of range of the reader, the rfid_TagLost event will happen. The code for the rfid_TagLost event handler follows:

void rfid_TagLost(object sender, TagEventArgs e){   txtTag.Text = "";   rfid1.LED = false;    // light off   lbPrevRFIDTags.Items.Insert(0,      string.Format("Tag: {0} - {1}", ++TagCtr, lastRFIDTag));}

In this routine, things are simply being cleaned up. The first line clears the textbox because no tag is currently being read. The second line turns off the LED light. The final line of code writes a line in the listbox showing the RFID tag information that was just read.

In your applications, the rfid_TagLost event would be the location where you could do your tag processing. The rfid_TagLost event will only happen once when the tag leaves the reader area. That makes this a better location for processing application logic than the rfid_Tag event. For example, for a system where members have an RFID membership card, this would be the area in the code where you would do a look up of your database system to find the unique Tag ID and then the associated member information.

You’ve now seen all the critical code—what little of it that was required. The sample also has two other event handlers and a few fields that have not been covered. These events and fields simply display information about the RFID reader such as whether it is attached as well as the serial number and version number of the reader: These events happen when the RFID reader attaches to or detaches from your system.

void rfid_Detach(object sender, DetachEventArgs e){   lblAttached.Text = "Not Attached";}void rfid_Attach(object sender, AttachEventArgs e){   Phidgets.RFID phid = (Phidgets.RFID)sender;   lblAttached.Text   = " Attached: " + phid.Name;   lblSerial.Text     = " Serial: "   + phid.SerialNumber;   lblVersion.Text    = " Version: "  + phid.Version;}


If this is your first time to see the code for reading RFID tags, you may be scratching your head wondering when it will get difficutlt. The answer is, it won’t—at least not with the PhidgetsRFID reader and their newest library. It really is just a mater of hooking up a reader, flipping a few property switches, and reading tags. Knowing it is this simple allows you to focus more on how to use RFID rather than on how to code for RFID usage.

The Source Files

Download the Source: 54 Kb

About the Author

Bradley Jones is a Microsoft MVP who works for Jupitermedia as an Executive Editor over many of the software development sites and channels. His experience includes development in C, C++, VB, some Java, C#, ASP, COBOL, and more as well as having been a developer, consultant, analyst, lead, and much more. His recent books include Teach Yourself the C# Language in 21 Days.

Listing 1: The PhidgetsForm.cs file:

using System;using System.Collections.Generic;using System.ComponentModel;using System.Data;using System.Drawing;using System.Text;using System.Windows.Forms;using Phidgets;using Phidgets.Events;namespace RFIDTest{   public partial class RFIDReader : Form   {      RFID   rfid1;      string lastRFIDTag;      Int32  TagCtr;      public RFIDReader()      {         InitializeComponent();         lastRFIDTag = "";         TagCtr = 0;      }      private void Form1_Load(object sender, EventArgs e)      {         rfid1 = new RFID();         rfid1.Attach      += new AttachEventHandler(rfid_Attach);         rfid1.Detach      += new DetachEventHandler(rfid_Detach);         rfid1.RFIDTag     += new TagEventHandler(rfid_Tag);         rfid1.RFIDTagLost += new TagEventHandler(rfid_TagLost);;      }      void rfid_Tag(object sender, TagEventArgs e)      {         txtTag.Text = e.Tag;         lastRFIDTag = txtTag.Text;         rfid1.LED   = true;    // light on      }      void rfid_TagLost(object sender, TagEventArgs e)      {         txtTag.Text = "";         rfid1.LED = false;    // light off         //write held Tag ID to listview         lbPrevRFIDTags.Items.Insert(0,            string.Format("Tag: {0} - {1}", ++TagCtr, lastRFIDTag));      }      void rfid_Detach(object sender, DetachEventArgs e)      {         lblAttached.Text = "Not Attached";      }      void rfid_Attach(object sender, AttachEventArgs e)      {         Phidgets.RFID phid = (Phidgets.RFID)sender;         lblAttached.Text   = "Attached: " + phid.Name;         lblSerial.Text     = " Serial: " + phid.SerialNumber;         lblVersion.Text    = " Version: " + phid.Version;      }      private void antennaCheckBox_CheckedChanged(         object sender, EventArgs e)      {         rfid1.Antenna = cboxAntenna.Checked;      }   }}

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories