Vous êtes sur la page 1sur 11

Visual C# Tutorial 1 Phidgets Inc.

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 firm 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 file, 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.
GUI Layout

A program with a GUI is composed of one or


more “forms”. The forms contain all of the ele-
2 ments necessary to interact with the computer
1 5 7
in a graphical environment. The form for this
4 program is the grey box on the screen. Most
3 3 programs that you will be writing for Phidgets,
at least to begin with, will only use one form.
6 Applications that make use of more than one
are often substantially more complicated to
program. The screen you see now is called
6 the “Form Designer”.

It is useful to first 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 first 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.


Visual C# Tutorial 1 Phidgets Inc.
Modify Properties

In this step, we’ll 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, first 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.
Text - Set this to “Antenna”. This checkbox is going to be
used to display the status of the RFID Reader’s antenna.

Once that is completed, the same process can be repeated for check-
Box2. However this time, set the Text property to “LED”.

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 file that
comes with Visual Studio.

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 it’s 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.


Visual C# Tutorial 1 Phidgets Inc.
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.

using System.Drawing; 1. Here we’ll add two “using” statements. “Us-


using System.Text;
using System.Windows.Forms; ing” statements allow us to specify specific
using Phidgets; namespaces to look for classes from our ref-
using Phidgets.Events; 1
erenced API libraries. In this case we are
namespace RFIDReader Specifying the “Phidgets” namespace and the
{ “Phidgets.Events” namespace. This clarifies the
public partial class Form1 : Form scope of a class. If we did not declare these
{
private RFID rfid; 2 using statements, we would have to use the full
namespace when declaring an object. In oth-
public Form1() er words, to create an RFID object, we would
{ 4 have to write “Phidget.RFID”, but since we de-
InitializeComponent();
3 } clared those using statements we can simply
write “RFID”.
private void Form1_Load(object sender,
EventArgs e) 2. Here the “rfid” object is declared. Note that we
{ declare the object outside of any subroutines
label1.Text = “Tag: -”; and therefore it remains globally accessible (ev-
label2.Text = “Status: Not
Connected”; ery subroutine can access it) within the scope
label3.Text = “Serial Number: -”; of this class, or more specifically, this Form. By
declaring the object this way, we are creating a
checkBox1.Checked = false;
reference to an RFID object which will be used
5 checkBox1.Enabled = false; 6
checkBox2.Checked = false; to point to a reserved place in memory that will
checkBox2.Enabled = false; hold a RFID object. Whenever we want to use
rfid = new RFID(); 2 that object we will refer to it using the reference
} we created.
.....
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 rfid object
we created earlier. This can be thought of as acting as the object in memory’s name for the purpose
of our application. So when using an object in code, such as rfid, 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.
3. This line of code was automatically created when we double clicked on the form in the form designer
and is used to define the subroutine.
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 specifics of this portion are not really important to most new us-
ers. In the simplest sense, it generates two objects, the first of which, sender, can be used to identify
the object or event responsible for triggering the subroutine. The second object, EventArgs e, con-


Visual C# Tutorial 1 Phidgets Inc.
tains other information that the subroutine is given. This structure containing sender and EventArgs
e objects is very common in .NET programming.
5. This three line block of code is responsible for changing the labels. The text shown on the check-
boxes was modified in the panel when laying out the GUI. Here however, the contents of the labels
are modified directly within the code. Most properties found in the properties panel can be modified
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 shouldn’t be able to modify the Antenna and LED properties
of the object.


Visual C# Tutorial 1 Phidgets Inc.
private void Form1_Load(object sender,
{
EventArgs e)
Handling the Phidget
label1.Text = “Tag: -”;
label2.Text = “Status: Not Connected”; It is now time to interface with the Phidget.
label3.Text = “Serial Number: -”;
As you can see in the code to the left, there
checkBox1.Checked = false; are three important events common to all
checkBox1.Enabled = false; Phidgets that must be handled, these are, at-
checkBox2.Checked = false;
checkBox2.Enabled = false; tach and detach, occurring when a Phidgets
1 USB cord is connected or removed from
rfid = new RFID(); the computer. Additionally, there is the er-
rfid.Attach += new AttachEventHandler(rfid_Attach); ror event which is called when the Phidget
rfid.Detach += new DetachEventHandler(rfid_Detach); malfunctions.
rfid.Error += new ErrorEventHandler(rfid_Error);
} 2 1. The “Attach” event is a subroutine
void rfid_Attach(object sender, AttachEventArgs e)
3 property of the RFID object. However,
{ the difference in the case of event han-
label1.Text = “Tag: -”; dlers is that we can “hook” more than
label2.Text = “Status: Connected”; 1
label3.Text = “Serial Number: “ + rfid. one handler subroutine to the event
SerialNumber.ToString(); handler property of the Phidget object.
To do this we use the “+=” operator,
checkBox1.Checked = rfid.Antenna;
checkBox1.Enabled = true; which simply means in this case “take
checkBox2.Checked = rfid.LED; the current list of event handlers and
checkBox2.Enabled = true; 4 add this new one”.
}

void rfid_Detach(object sender, DetachEventArgs e) When writing this line of code, you will
{ be given the option to “auto complete”
label1.Text = “Tag: -”;
label2.Text = “Status: Not Connected”; the line of code by simply pressing the
label3.Text = “Serial Number: -”; tab key to fill in the rest automatically.
2 If you do this, it will automatically gen-
checkBox1.Checked = false;
checkBox1.Enabled = false; erate the subroutine for the rfid_Attach
checkBox2.Checked = false; event handler below.
checkBox2.Enabled = false; 2. As with the “Attach” event handler
} 5 above, repeat this process for the “De-
void rfid_Error(object sender, ErrorEventArgs e) tach” event. If you auto complete the
{ code, it will automatically generate the
MessageBox.Show(e.Description);
3 rfid_Detach event handler subroutine
rfid.close(); below as before.
this.Close();
} 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 rfid_Error event handler subroutine below as
before.


Visual C# Tutorial 1 Phidgets Inc.
4. Now we will look at doing the work that we want done whenever an Attach event is triggered.
Firstly, when the rfid_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 isn’t finished being coded yet. We are going to remedy that right
now.

The first 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 Phidget’s serial number, stored in the Serial Number proper-
ty of the rfid 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 isn’t always necessary, however
some controls don’t 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 rfid 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 finally, set the Enabled property for both checkboxes to true so we can
change the values.
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 can’t 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
first we will create a MessageBox object and display the error description which is a property of
the ErrorEventArgs object e using the messagebox’s 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 rfid 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.


Visual C# Tutorial 1 Phidgets Inc.
private void Form1_Load(object sender,
e)
EventArgs
Handling the Tag Events
{
label1.Text = “Tag: -”; Now we must handle the RFID phidget specific
label2.Text = “Status: Not
Connected”; events; the Tag events. The tag events are trig-
label3.Text = “Serial Number: -”; gered when an RFID tag is brought into antenna
scan range of the phidget and when a tag is taken
checkBox1.Checked = false;
checkBox1.Enabled = false; out of range, Tag and TagLost respectively.
checkBox2.Checked = false;
checkBox2.Enabled = false; 1. The “Tag” is an event that is specific to an RFID
rfid = new RFID(); Phidget class. We hook this event subroutine
rfid.Attach += new AttachEventHandler(rfid_ exactly the same as the Attach, Detach, and Er-
Attach); ror event subroutines as before using the +=
rfid.Detach += new DetachEventHandler(rfid_
Detach); operator.

1 rfid.Error += new ErrorEventHandler(rfid_
Error); Also like before, we can use the auto complete
rfid.Tag += new TagEventHandler(rfid_Tag); by pressing the Tab key to automatically gen-
rfid.TagLost += new TagEventHandler(rfid_ erate the rfid_Tag subroutine code. Note the
TagLost);
method signature for this event, it uses a Ta-
}
void rfid_Tag(object sender, TagEventArgs e) gEventArgs object specific to the tag events.
{ 2
label1.Text = “Tag: “ + e.Tag;
}
3
void rfid_TagLost(object sender, TagEventArgs e)
2. As with the Tag event above, repeat this pro-
{ cess for the TagLost event. As before, if you
label1.Text = “Tag: -”; 4 auto complete using the Tab key it will auto
}
generate the rfid_TagLost event handler sub-
routine below.
3. Now we will write the code to do the work we want done whenever a rfid_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 label1’s 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, specifically the Tag
value of the scanned tag. So we will display this value in the label’s text. Your code should look
like what is shown above in the rfid_Tag event handler subroutine
4. Now we will write the code to do the work we want done whenever a rfid_TagLost event is trig-
gered. When a tag is lost, it means there is no tag in range to scan, so we should reset label1’s
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.


Visual C# Tutorial 1 Phidgets Inc.
At this point the application is nearly complete. If you choose to test it at this stage, bringing an rfid
tag in range of the RFID Reader will display the tag value in the first 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)
Linking the Phidget to the Check-
label1.Text = “Tag: -”; boxes
label2.Text = “Status: Not Connected”;
label3.Text = “Serial Number: -”;
Now we will link the checkboxes to the RFID
checkBox1.Checked = false; phidgets. In other words, when the user clicks
checkBox1.Enabled = false; the checkboxes, we need to have code that
checkBox2.Checked = false;
checkBox2.Enabled = false; will modify the Phidget.

rfid = new RFID(); 1. Calling the .open() subroutine on our rfid


rfid.Attach += new AttachEventHandler(rfid_ object specifically tells rfid to search the
Attach); computer’s USB ports and try and detect
rfid.Detach += new DetachEventHandler(rfid_
Detach);
any Phidget RFIDs already connected. If it
rfid.Error += new ErrorEventHandler(rfid_Error); finds any, it then proceeds to call the Attach
subroutine that you have already written.
rfid.Tag += new TagEventHandler(rfid_Tag);
rfid.TagLost += new TagEventHandler(rfid_TagLost);
The .open() subroutine called here is in fact
2 an element common to any Phidget ob-
rfid.open(); 1 ject that you create. Just as Phidgets.RFID
}
was used to create the rfid object used
private void checkBox1_CheckedChanged(object sender, here to interact with the RFID Reader, a
EventArgs e) Phidgets.Servo object would interact with a
{
rfid.Antenna = checkBox1.Checked;
Servo motor control. Both objects would
}
3 contain a number of common properties
and subroutines, including .open() and the
private void checkBox2_CheckedChanged(object sender,
EventArgs e)
basic events Attach, Detach, and Error. A
{ complete list can be found in the .NET API
rfid.LED = checkBox2.Checked; manual.
}
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 rfid object as shown in the code above. Whenever
the checkbox is clicked, this event will be triggered and change the value in the rfid object for us.


Visual C# Tutorial 1 Phidgets Inc.
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 rfid object as shown in the code above. Whenever the
checkbox is clicked, this event will be triggered and change the value in the rfid object for us.

Closing Subroutines

The final step that must be accounted for is exiting the program and shutting everything down cleanly.

Generating the Form1_FormClosing subroutine:

1 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 )
2
3
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).

private void Form1_FormClosing(object sender, Writing the closing subroutine code:


FormClosingEventArgs e)
{
rfid.Attach -= new AttachEventHandler(rfid_Attach); The Form1_FormClosing subroutine ( 1 )
rfid.Detach -= new DetachEventHandler(rfid_Detach); was auto generated in the last step from
rfid.Error -= new ErrorEventHandler(rfid_Error);
the Form Designer view. This event is trig-

1 rfid.Tag -= new TagEventHandler(rfid_Tag); gered when Form1 is being closed, either
rfid.TagLost -= new TagEventHandler(rfid_TagLost); from this.close() or by clicking the “X” button
on the top right corner of the form like most
rfid.close(); 3
windows applications.
2

}
rfid = null; 4
First thing we will do in the closing subrou-
tine is “unhook” the event handlers that we
had hooked to the rfid 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-

10
Visual C# Tutorial 1 Phidgets Inc.
gered while we are trying to close the application, it will essentially ignore is since we have no handler
specified 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 rfid 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.

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 rfid
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.

11