You are on page 1of 11

Visual C# Tutorial 1 Phidgets Inc.

1
Visual C# Tutorial 1
A Single RFID Reader in Visual C#
Overview
In this tutorial we will cover:
Initial setup
Creating the Graphical User Interface
Writing code to operate the Graphical User Interface and control a Phidget RFID reader
This tutorial provides a starting point for learning how to use the Phidget RFID Reader and develop a
feel for the way all Phidgets work. This tutorial is targeted towards those who are new to C# Program-
ming and creating Graphical User Interfaces. However, this tutorial assumes the reader possesses
an understanding of basic programming concepts. Knowledge of object oriented programming is also
assumed.
The source code for this application is provided with the tutorial. It is suggested though that you follow
the steps outlined here to gain a frm grasp of how Visual C# works and the steps used to create the
application. More examples are available in the Downloads section of the web site.
Initial Setup
Please ensure that you have a working copy of Visual Studio (Visual Studio or Visual C# Express)
installed on your system, and that it is up to date.
Important: It is necessary to download and install the Phidget21 .NET API from the Phidgets web
site, Phidget21.msi. Without this fle, it is not possible to use Phidgets.
Creating the Graphical User Interface (GUI)
The GUI is what you actually see when running your program. It allows you to interact with the code
and make changes that can affect your Phidget.
Create a New Project
To begin, open Visual Studio and create a new project. Select Windows Application, name the project
RFIDReader and click Ok.
Visual C# Tutorial 1 Phidgets Inc.
2
GUI Layout
A program with a GUI is composed of one or
more forms. The forms contain all of the ele-
ments necessary to interact with the computer
in a graphical environment. The form for this
program is the grey box on the screen. Most
programs that you will be writing for Phidgets,
at least to begin with, will only use one form.
Applications that make use of more than one
are often substantially more complicated to
program. The screen you see now is called
the Form Designer.
It is useful to frst set up your workspace. If
the Toolbox panel is not already visible, open the View menu ( 1 ) and select Toolbox. To ensure
the Toolbox panel does not cover the form you are going to be working on, toggle the pin button ( 2
).
The various elements of the GUI, known as controls, can be placed in whatever order you wish and in
any location you wish within the form. For this example, we will frst place the Labels( 3 ) which will be
used to display information. Under the All Windows Forms rollout, select Label. Click somewhere in
the middle and upper region of the form. Repeat this action to create three labels. label1 will be used
to display the tag code whenever an RFID tag is brought into the scanning distance of the antenna.
label2 will be used to represent the connection status of the RFID reader, and label3 will be used to
display the serial number of the connected Phidget. Note the names of your labels and the order they
appear on the form, they should follow the order shown here.
When working with the labels and controls in general, it is often useful to open the layout toolbar by
selecting View ( 1 ) >> Toolbars >> Layout. The layout toolbar provides many helpful tools for aligning
elements on the form. Select the three labels you created and perform a Left Align ( 4 ). If your labels
are spread out vertically you can also try clicking Make Vertical Spacing Equal ( 5 ). You can move
the labels as a group into whatever position you wish.
Finally, select the CheckBox tool ( 6 ) and as in the same manner as the labels, create a checkbox un-
der the labels. Repeat this process to create a second checkbox under the previously created check-
box. Select the two checkboxes and click Center Horizontally ( 7 ) on the layout toolbar.
At this stage, experimentation is encouraged to create a satisfactory look.
1
2
3
3
4
5
6
7
6
Visual C# Tutorial 1 Phidgets Inc.
3
Modify Properties
In this step, well modify the labels attached to the two checkboxes
we created to display something a little bit more meaningful to our ex-
ample. To do this we will have to modify those controls Properties.
To do this, frst click on checkBox1 to select it and look to the bottom
right hand side of the screen. The properties panel should be visible
with the name of the selected control at the top of the panel. Here the
name is checkBox1. We will be changing the following properties:
1.

Once that is completed, the same process can be repeated for check-
Box2. However this time, set the Text property to LED.
Text - Set this to Antenna. This checkbox is going to be
used to display the status of the RFID Readers antenna.
Writing the Code
Visual C# and all visual programming languages are event driven, as such, any action you want the
program to respond to calls a subroutine. As a general rule, every event requires its own block of
code. There are three categories of action that this application must be designed to handle.
1. Program Activities - These are events such as opening or closing the program.
2. User Activities - Such as clicking the Antenna or LED checkboxes.
3. Phidget Events - Phidget events include attaching or detaching the Phidget and handling
any errors that might occur.
As is obvious, there are many different properties that can be set. A fairly good explanation can be
found by clicking on each and looking to the very bottom of the screen or by searching the help fle that
comes with Visual Studio.
Visual C# Tutorial 1 Phidgets Inc.
4
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using Phidgets;
using Phidgets.Events;
namespace RFIDReader
{
public partial class Form1 : Form
{
private RFID rfd;
public Form1()
{
InitializeComponent();
}
private void Form1_Load(object sender,
EventArgs e)
{
label1.Text = Tag: -;
label2.Text = Status: Not
Connected;
label3.Text = Serial Number: -;
checkBox1.Checked = false;
checkBox1.Enabled = false;
checkBox2.Checked = false;
checkBox2.Enabled = false;
rfd = new RFID();
}
.....
1. Here well add two using statements. Us-
ing statements allow us to specify specifc
namespaces to look for classes from our ref-
erenced API libraries. In this case we are
Specifying the Phidgets namespace and the
Phidgets.Events namespace. This clarifes the
scope of a class. If we did not declare these
using statements, we would have to use the full
namespace when declaring an object. In oth-
er words, to create an RFID object, we would
have to write Phidget.RFID, but since we de-
clared those using statements we can simply
write RFID.
2. Here the rfd object is declared. Note that we
declare the object outside of any subroutines
and therefore it remains globally accessible (ev-
ery subroutine can access it) within the scope
of this class, or more specifcally, this Form. By
declaring the object this way, we are creating a
reference to an RFID object which will be used
to point to a reserved place in memory that will
hold a RFID object. Whenever we want to use
that object we will refer to it using the reference
we created.
3. This line of code was automatically created when we double clicked on the form in the form designer
and is used to defne the subroutine.
Now, observe later on in the code how we create the new RFID object in memory using new RFID().
This reserves the space for memory for the object and then creates the reference to our rfd object
we created earlier. This can be thought of as acting as the object in memorys name for the purpose
of our application. So when using an object in code, such as rfd, you are actually not using the
object but the reference to the object. For example, it is possible to have two objects (A and B) and
to swap their references. In such a case, calling object A would actually access object B.
4. As with ( 3 ), this portion of this line of code was also automatically created when we double clicked
the form in the form designer. The specifcs of this portion are not really important to most new us-
ers. In the simplest sense, it generates two objects, the frst of which, sender, can be used to identify
the object or event responsible for triggering the subroutine. The second object, EventArgs e, con-
Form Load Event
While still in the Form Designer, double-click the form in order to generate the code block to handle a
Load event for our form. This subroutine is triggered when the application is opened. After double-
clicking the form, a new window tab should be opened display the Code View for our form with a new
block of code for our Form1_Load event.
2
5 6
3
4
2
1
Visual C# Tutorial 1 Phidgets Inc.
5
5. This three line block of code is responsible for changing the labels. The text shown on the check-
boxes was modifed in the panel when laying out the GUI. Here however, the contents of the labels
are modifed directly within the code. Most properties found in the properties panel can be modifed
by the code in this same manner. The structure object.property or object.variable is a universal way
of accessing or modifying information within objects. If the call contains brackets, it is a subrou-
tine, such as object.subroutine(). It is also possible to have layered structures, as in object.property.
property.subroutine(). In this case, the property actually refers to another object contained within the
main object.
6. This block of code is responsible for changing some properties of the checkboxes. In this block we
are clearing the checkboxes so that they will look unchecked. We are also changing the enabled
property to false. Doing this will make them unusable. This is due to the fact that at this point there
is no RFID device attached so the use shouldnt be able to modify the Antenna and LED properties
of the object.
tains other information that the subroutine is given. This structure containing sender and EventArgs
e objects is very common in .NET programming.
Visual C# Tutorial 1 Phidgets Inc.
6
3. As with the Detach event handler above, repeat this process for the Error event. If you auto
complete the code, it will automatically generate the rfd_Error event handler subroutine below as
before.
Handling the Phidget
It is now time to interface with the Phidget.
As you can see in the code to the left, there
are three important events common to all
Phidgets that must be handled, these are, at-
tach and detach, occurring when a Phidgets
USB cord is connected or removed from
the computer. Additionally, there is the er-
ror event which is called when the Phidget
malfunctions.
1.
The Attach event is a subroutine
property of the RFID object. However,
the difference in the case of event han-
dlers is that we can hook more than
one handler subroutine to the event
handler property of the Phidget object.
To do this we use the += operator,
which simply means in this case take
the current list of event handlers and
add this new one.
When writing this line of code, you will
be given the option to auto complete
the line of code by simply pressing the
tab key to fll in the rest automatically.
If you do this, it will automatically gen-
erate the subroutine for the rfd_Attach
event handler below.
2. As with the Attach event handler
above, repeat this process for the De-
tach event. If you auto complete the
code, it will automatically generate the
rfd_Detach event handler subroutine
below as before.
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = Tag: -;
label2.Text = Status: Not Connected;
label3.Text = Serial Number: -;
checkBox1.Checked = false;
checkBox1.Enabled = false;
checkBox2.Checked = false;
checkBox2.Enabled = false;
rfd = new RFID();
rfd.Attach += new AttachEventHandler(rfd_Attach);
rfd.Detach += new DetachEventHandler(rfd_Detach);
rfd.Error += new ErrorEventHandler(rfd_Error);
}
void rfd_Attach(object sender, AttachEventArgs e)
{
label1.Text = Tag: -;
label2.Text = Status: Connected;
label3.Text = Serial Number: + rfd.
SerialNumber.ToString();
checkBox1.Checked = rfd.Antenna;
checkBox1.Enabled = true;
checkBox2.Checked = rfd.LED;
checkBox2.Enabled = true;
}
void rfd_Detach(object sender, DetachEventArgs e)
{
label1.Text = Tag: -;
label2.Text = Status: Not Connected;
label3.Text = Serial Number: -;
checkBox1.Checked = false;
checkBox1.Enabled = false;
checkBox2.Checked = false;
checkBox2.Enabled = false;
}
void rfd_Error(object sender, ErrorEventArgs e)
{
MessageBox.Show(e.Description);
rfd.close();
this.Close();
}
3
1
2
1
4
2
5
3
6
Visual C# Tutorial 1 Phidgets Inc.
7
5. For the Detach event, we simply have to restore the values of the labels and checkboxes to what
we and set them to initially in the Form1_Load subroutine to show that a Phidget RFID is not con-
nected and make it so the user cant modify the value of the checkboxes. So we can copy the
code used earlier in the Form1_Load subroutine again here.
6. For the Error event, we want to display the error that occurred and to shut down the program. So
frst we will create a MessageBox object and display the error description which is a property of
the ErrorEventArgs object e using the messageboxs show() subroutine. The error description is a
property of the ErrorEventArgs object.
After displaying the message box with the error description, we will close the rfd object by calling
its close() subroutine and we will do the same for the form by calling its close() subroutine. this
in this case is referring to the form which is the current object of the class that we are running this
code inside of.
4. Now we will look at doing the work that we want done whenever an Attach event is triggered.
Firstly, when the rfd_Attach event handler subroutine was auto generated, it created a throw
statement in the subroutine body. Delete that as it is not necessary as it only serves to warn you
and the user that the subroutine isnt fnished being coded yet. We are going to remedy that right
now.
The frst thing we want to do in an Attach event is change the text being displayed in the labels.
So modify the text in label2 to read Status: Connected to show that a Phidget RFID is now con-
nected to the computer. Next, change the text for label3 to read Serial Number: . We will then
add the value of the connected RFID Phidgets serial number, stored in the Serial Number proper-
ty of the rfd object, to the string displayed by the label by using the + also known as the append
operator. The toString() subroutine for the Serial Number property will change the Serial Number
from a number to a printable string version of the number. This isnt always necessary, however
some controls dont like you sending non-string values to some of their properties so it is often
best practice to use the toString() subroutine of number values before displaying them in a string
based control.
Lastly, we want to display the working status of the RFID Antenna and LED. There is a property
for both Antenna and LED in the rfd object. Both of these properties are bool data types which
mean they have two values: true or false. The checkbox control Checked property also uses this
bool value so we can simply set the Checked property to equal the bool value of the Antenna and
LED properties. Then fnally, set the Enabled property for both checkboxes to true so we can
change the values.
Visual C# Tutorial 1 Phidgets Inc.
8
Handling the Tag Events
Now we must handle the RFID phidget specifc
events; the Tag events. The tag events are trig-
gered when an RFID tag is brought into antenna
scan range of the phidget and when a tag is taken
out of range, Tag and TagLost respectively.
1. The Tag is an event that is specifc to an RFID
Phidget class. We hook this event subroutine
exactly the same as the Attach, Detach, and Er-
ror event subroutines as before using the +=
operator.
Also like before, we can use the auto complete
by pressing the Tab key to automatically gen-
erate the rfd_Tag subroutine code. Note the
method signature for this event, it uses a Ta-
gEventArgs object specifc to the tag events.
2. As with the Tag event above, repeat this pro-
cess for the TagLost event. As before, if you
auto complete using the Tab key it will auto
generate the rfd_TagLost event handler sub-
routine below.
3. Now we will write the code to do the work we want done whenever a rfd_Tag event is triggered.
Since we created a label to display the tag value, in this subroutine we will modify the text that the
label will display to display the tag value.
So in this subroutine, we will change label1s Text property to be Tag: and we will append the
Tag value property from object e which is a TagEventArgs object. The TagEventArgs object is an
object sent during an event that contains the information related to the event, specifcally the Tag
value of the scanned tag. So we will display this value in the labels text. Your code should look
like what is shown above in the rfd_Tag event handler subroutine
private void Form1_Load(object sender, EventArgs
e)
{
label1.Text = Tag: -;
label2.Text = Status: Not
Connected;
label3.Text = Serial Number: -;
checkBox1.Checked = false;
checkBox1.Enabled = false;
checkBox2.Checked = false;
checkBox2.Enabled = false;
rfd = new RFID();
rfd.Attach += new AttachEventHandler(rfd_
Attach);
rfd.Detach += new DetachEventHandler(rfd_
Detach);
rfd.Error += new ErrorEventHandler(rfd_
Error);
rfd.Tag += new TagEventHandler(rfd_Tag);

}
void rfd_Tag(object sender, TagEventArgs e)
{
label1.Text = Tag: + e.Tag;
}
void rfd_TagLost(object sender, TagEventArgs e)
{
label1.Text = Tag: -;
}
4. Now we will write the code to do the work we want done whenever a rfd_TagLost event is trig-
gered. When a tag is lost, it means there is no tag in range to scan, so we should reset label1s
Text property to show that. To do this, we can simply copy the code we used to initialize label1 in
the Form1_Load subroutine. In other words, the code should be label1.Text = Tag: -; as
shown above.
1
2
3
4
rfd.TagLost += new TagEventHandler(rfd_
TagLost);
Visual C# Tutorial 1 Phidgets Inc.
9
Linking the Phidget to the Check-
boxes
Now we will link the checkboxes to the RFID
phidgets. In other words, when the user clicks
the checkboxes, we need to have code that
will modify the Phidget.
1.
Calling the .open() subroutine on our rfd
object specifcally tells rfd to search the
computers USB ports and try and detect
any Phidget RFIDs already connected. If it
fnds any, it then proceeds to call the Attach
subroutine that you have already written.
The .open() subroutine called here is in fact
an element common to any Phidget ob-
ject that you create. Just as Phidgets.RFID
was used to create the rfd object used
here to interact with the RFID Reader, a
Phidgets.Servo object would interact with a
Servo motor control. Both objects would
contain a number of common properties
and subroutines, including .open() and the
basic events Attach, Detach, and Error. A
complete list can be found in the .NET API
manual.
At this point the application is nearly complete. If you choose to test it at this stage, bringing an rfd
tag in range of the RFID Reader will display the tag value in the frst label when a Phidget RFID
Reader is connected. When the checkboxes are clicked, it should turn on and off the Antenna and
LED on the RFID Reader.
private void Form1_Load(object sender, EventArgs e)
{
label1.Text = Tag: -;
label2.Text = Status: Not Connected;
label3.Text = Serial Number: -;
checkBox1.Checked = false;
checkBox1.Enabled = false;
checkBox2.Checked = false;
checkBox2.Enabled = false;
rfd = new RFID();
rfd.Attach += new AttachEventHandler(rfd_
Attach);
rfd.Detach += new DetachEventHandler(rfd_
Detach);
rfd.Error += new ErrorEventHandler(rfd_Error);
rfd.Tag += new TagEventHandler(rfd_Tag);
rfd.TagLost += new TagEventHandler(rfd_TagLost);
rfd.open();
}
private void checkBox1_CheckedChanged(object sender,
EventArgs e)
{
rfd.Antenna = checkBox1.Checked;
}
private void checkBox2_CheckedChanged(object sender,
EventArgs e)
{
rfd.LED = checkBox2.Checked;
}
2. In the Form Designer window in Visual Studio, double click on the antenna checkbox to generate
the checkBox1_CheckedChanged event handler subroutine in the same fashion that we generated
the Form1_Load subroutine earlier. This subroutine will allow us to modify the status of the Antenna
property of the Phidget RFID, in essence allowing us to turn on and off the Antenna on the Phidget
RFID.
In order to do so we simply have to assign the current Checked property value of checkBox1 (the an-
tenna checkbox) to the Antenna property of our rfd object as shown in the code above. Whenever
the checkbox is clicked, this event will be triggered and change the value in the rfd object for us.
2
3
1
Visual C# Tutorial 1 Phidgets Inc.
10
Generating the Form1_FormClosing subroutine:
First, open the Form Designer window once again and select the
main Form. Look to the properties window at the bottom right of
the screen, it should list the properties for Form1 right now.( 1 )
Select the Events menu by clicking the button that looks like a
lightning bolt on the properties window. ( 2 ) Finally, locate the
FormClosing event in the list of available events for the selected
Form control.( 3 ) Double click the FormClosing event in order to
auto generate the Form1_FormClosing event handler subroutine in
the code view (shown in the next image).
Closing Subroutines
The fnal step that must be accounted for is exiting the program and shutting everything down cleanly.
3. As before, double click on the LED checkbox to generate the checkBox2_CheckedChanged event
handler subroutine. This subroutine will allow us to modify the status of the LED property of the
Phidget RFID, in essence allowing us to turn on and off the LED on the Phidget RFID.
In order to do so we simply have to assign the current Checked property value of checkBox2 (the
LED checkbox) to the LED property of our rfd object as shown in the code above. Whenever the
checkbox is clicked, this event will be triggered and change the value in the rfd object for us.
Writing the closing subroutine code:
The Form1_FormClosing subroutine ( 1 )
was auto generated in the last step from
the Form Designer view. This event is trig-
gered when Form1 is being closed, either
from this.close() or by clicking the X button
on the top right corner of the form like most
windows applications.
First thing we will do in the closing subrou-
tine is unhook the event handlers that we
had hooked to the rfd object in the Form1_
Load subroutine.( 2 ) What this does in
effect is disconnects the event handlers
that we created so that if an event is trig-
private void Form1_FormClosing(object sender,
FormClosingEventArgs e)
{
rfd.Attach -= new AttachEventHandler(rfd_Attach);
rfd.Detach -= new DetachEventHandler(rfd_Detach);
rfd.Error -= new ErrorEventHandler(rfd_Error);
rfd.Tag -= new TagEventHandler(rfd_Tag);
rfd.TagLost -= new TagEventHandler(rfd_TagLost);
rfd.close();
rfd = null;
}
3
1
2
1
2
3
4
Visual C# Tutorial 1 Phidgets Inc.
11
Conclusion
You have now completed creating the application. You should now be able to run it (the green arrow).
Connect a Phidget RFID Reader and try bringing an RFID tag close to the RFID Reader and taking it
away and noting the Tag display label. It should now display the tag value of the tag that was brought
in scanning range of the Reader. You should also now be able to disable and enable the Antenna
and onboard LED.
Hopefully you now have a better understanding of Phidgets and how to begin programming with
them. Every Phidget works in the same fundamental way so if you understand the creation of the rfd
object, how it is used and how to modify its properties, you are well on your way to being able to use
almost any Phidget.
It is very important to note what you have learned in this tutorial is suitable for dealing with only one
Phidget connected to the computer. If you have two or more of the same type, you will get unreliable
results and not know which one the program will control. A simple method for dealing with this issue
is discussed in a later tutorial.
gered while we are trying to close the application, it will essentially ignore is since we have no handler
specifed to handle the event. This can prevent a few errors that occur during the closing phase.
Though not essential, it is recommended to use the .close() subroutine when a given Phidget object
is no longer required.( 3 ) It does not delete the object, rather it disconnects the current Phidget from
the program. If you wanted to use the Phidget after this command (which is not applicable in this
case as the program is closing), you would need to once again call the .open() subroutine.
Finally, we will set the rfd object to null to clear its reference to the RFID object we created.( 4 ) This
will signal the system that the object is no longer in use and can be removed from memory once the
application is closed.

You might also like