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

C Sharp Tutorial

Embed Size (px)

DESCRIPTION

c sharp is a lot like java. here is a tutorial for beginning to program in visual C sharp distributed free by microsoft.

Citation preview

Page 1: C Sharp Tutorial

Visual C# Tutorial 1 Phidgets Inc.

1

Visual C# Tutorial 1A 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”.

Page 2: C Sharp Tutorial

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

12

3 34

5

6

7

6

Page 3: C Sharp Tutorial

Visual C# Tutorial 1 Phidgets Inc.

3

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.

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 Reader’s antenna.

Writing the CodeVisual 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.

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.

Page 4: C Sharp Tutorial

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

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;

rfid = new RFID(); }.....

1. Here we’ll add two “using” statements. “Us-ing” statements allow us to specify specific 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 clarifies 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 “rfid” 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 specifically, 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 define 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 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.

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-

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

34

2

1

Page 5: C Sharp Tutorial

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

tains other information that the subroutine is given. This structure containing sender and EventArgs e objects is very common in .NET programming.

Page 6: C Sharp Tutorial

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 rfid_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 fill in the rest automatically. If you do this, it will automatically gen-erate the subroutine for the rfid_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 rfid_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;

rfid = new RFID();

rfid.Attach += new AttachEventHandler(rfid_Attach); rfid.Detach += new DetachEventHandler(rfid_Detach); rfid.Error += new ErrorEventHandler(rfid_Error);}

void rfid_Attach(object sender, AttachEventArgs e){ label1.Text = “Tag: -”; label2.Text = “Status: Connected”; label3.Text = “Serial Number: “ + rfid.SerialNumber.ToString();

checkBox1.Checked = rfid.Antenna; checkBox1.Enabled = true; checkBox2.Checked = rfid.LED; checkBox2.Enabled = true;}

void rfid_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 rfid_Error(object sender, ErrorEventArgs e){ MessageBox.Show(e.Description);

rfid.close(); this.Close();}

3

1

2

1

4

2

5

3

6

Page 7: C Sharp Tutorial

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

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.

Page 8: C Sharp Tutorial

Visual C# Tutorial 1 Phidgets Inc.

Handling the Tag Events

Now we must handle the RFID phidget specific 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 specific 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 rfid_Tag subroutine code. Note the method signature for this event, it uses a Ta-gEventArgs object specific 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 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

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;

rfid = new RFID(); rfid.Attach += new AttachEventHandler(rfid_Attach); rfid.Detach += new DetachEventHandler(rfid_Detach); rfid.Error += new ErrorEventHandler(rfid_Error);

rfid.Tag += new TagEventHandler(rfid_Tag);

}void rfid_Tag(object sender, TagEventArgs e){ label1.Text = “Tag: “ + e.Tag;}

void rfid_TagLost(object sender, TagEventArgs e){ label1.Text = “Tag: -”;}

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.

1

2

3

4

rfid.TagLost += new TagEventHandler(rfid_TagLost);

Page 9: C Sharp Tutorial

Visual C# Tutorial 1 Phidgets Inc.

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 rfid object specifically tells rfid to search the computer’s USB ports and try and detect any Phidget RFIDs already connected. If it finds 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 rfid 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 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) { label1.Text = “Tag: -”; label2.Text = “Status: Not Connected”; label3.Text = “Serial Number: -”;

checkBox1.Checked = false; checkBox1.Enabled = false; checkBox2.Checked = false; checkBox2.Enabled = false;

rfid = new RFID();

rfid.Attach += new AttachEventHandler(rfid_Attach); rfid.Detach += new DetachEventHandler(rfid_Detach); rfid.Error += new ErrorEventHandler(rfid_Error);

rfid.Tag += new TagEventHandler(rfid_Tag); rfid.TagLost += new TagEventHandler(rfid_TagLost);

rfid.open();}

private void checkBox1_CheckedChanged(object sender, EventArgs e){ rfid.Antenna = checkBox1.Checked;}

private void checkBox2_CheckedChanged(object sender, EventArgs e){ rfid.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 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.

2

3

1

Page 10: C Sharp Tutorial

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

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

private void Form1_FormClosing(object sender, FormClosingEventArgs e){ rfid.Attach -= new AttachEventHandler(rfid_Attach); rfid.Detach -= new DetachEventHandler(rfid_Detach); rfid.Error -= new ErrorEventHandler(rfid_Error);

rfid.Tag -= new TagEventHandler(rfid_Tag); rfid.TagLost -= new TagEventHandler(rfid_TagLost);

rfid.close();

rfid = null;}

3

1

2

1

23

4

Page 11: C Sharp Tutorial

Visual C# Tutorial 1 Phidgets Inc.

11

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

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.