Click here to Skip to main content
15,881,812 members
Articles / Desktop Programming / Windows Forms
Tip/Trick

Serial Port Communication

Rate me:
Please Sign up or sign in to vote.
4.80/5 (15 votes)
8 Apr 2012CPOL2 min read 155.5K   29   8
Serial Communication with the .NET Framework in Winforms

Introduction

Serial port data can be read in many ways and many devices communicate via the serial port. In my project I had the need to implement serial port communication for a RFID reader. This is a sample example to read data from the serial port and display on the Windows Forms TextBox control.

Using the code

To begin, let's create a C# Windows Forms application in Visual Studio 2008 (hope it will work in VS 2005/2010 also, though not tested by myself). Add a textbox, a button control and  a SerialPort control on to the form.

Declare a string variable as private:

C#
private string DispString;   //used to store the values read

In the form Load event , write the code as shown below:

C#
private void Form1_Load(object sender, EventArgs e)
{
    //Port name can be identified by checking the ports
    // section in Device Manager after connecting your device
    serialPort1.PortName = "COM5";
    //Provide the name of port to which device is connected

    //default values of hardware[check with device specification document]
    serialPort1.BaudRate = 9600;  
    serialPort1.Parity = Parity.None; 
    serialPort1.StopBits = StopBits.One; 
    serialPort1.Handshake = Handshake.None;

    serialPort1.Open(); //opens the port
    serialPort1.ReadTimeout = 200; 
    if (serialPort1.IsOpen)
    {
        DispString = "";
        txtCardKeyDeactivate.Text = "";
    }
    serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived);
}

Although the code is self explanatory, I will explain little.

When the application starts, the serial port is opened to read the received data,you need to set up an event.

C#
serialPort1.DataReceived += new SerialDataReceivedEventHandler(serialPort1_DataReceived); 

It is always better to set up the event before the serial port is opened.

Now lets declare an event handler to handle the event. The code to manipulate the read data can be specified here.

C#
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    if (textBox1.Text.Length >= 12)
    {
        serialPort1.Close(); //call your own method to perform some operation
    }
    else
    {
        DispString = serialPort1.ReadExisting();
        this.Invoke(new EventHandler(DisplayText));
    }
}

In my example the RFID tag had 12 letters value and only one card need to be read till a particular operation is completed. So, I have set a condition to close the port if string variable has length of 12. Actually RFID readers can read more than 100 tags per minute. Then you can store the values in some array and according to your need you can manipulate them. But if your tags have the same count like 878BGFFJJJHG, 78766HGGBVVV and you have to make sure that each tag is read then you can specify some condition like the above code.

You can use threading also but if you don't like to use threading then you can use a condition.

C#
DispString = serialPort1.ReadExisting();

I insist that you should use condition as the above code for a tag [78766HGGBVVV] may return values of one letter at a time and it will be very fast. So to make sure that a tag has been read completely find the length and use the condition to do some operation or read another tag.

Now, you can't assign the value read directly to a textbox in the same event handler as it will throw some exception. You have to use the Invoke method to call your method, which can do the appending work in case of  my program or manipulation work in your problem  etc.  

C#
this.Invoke(new EventHandler(DisplayText));

The below DisplayText method is called  by the invoke method.

C#
private void DisplayText(object sender, EventArgs e)
{
    textBox1.AppendText(DispString);
}

After the read operation is completed make sure you close the serial port.

C#
if (serialPort1.IsOpen) 
serialPort1.Close();

Points of Interest  

There are many ways to read data from serial port.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
Student
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
QuestionRead rfid card information in visual studio 2013 without button Pin
Member 1161948319-Apr-15 1:41
Member 1161948319-Apr-15 1:41 
Questionhow can receive data from virtual port? Pin
Member 1146776227-Feb-15 10:36
Member 1146776227-Feb-15 10:36 
QuestionHow can I get source code? Pin
Member 4595213-Jan-14 6:29
Member 4595213-Jan-14 6:29 
Questionweird characters Pin
Doğan Etkin Irmaklı9-Oct-13 4:14
Doğan Etkin Irmaklı9-Oct-13 4:14 
Questionwhat if the data with header and footer Pin
gambrenk17-Sep-13 5:43
gambrenk17-Sep-13 5:43 
QuestionRFID WRITE Pin
Pradeep.1july8-May-12 15:54
Pradeep.1july8-May-12 15:54 
SuggestionRe: RFID WRITE Pin
Sreedeep.S10-May-12 22:25
Sreedeep.S10-May-12 22:25 
I hope you would like to know whether the data written to RFID tag was successful or not..I don't know what kind of device or tags you are using..but I could suggest you that if you just like to make sure whether the data has been properly written , why don't you do a read operation just after the write operation.
if (read_data == written_data )
{
 //means write was successful.So, display some message
}

QuestionHow can I get source code? Pin
Member 4595213-Jan-14 6:28
Member 4595213-Jan-14 6:28 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Praise Praise    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.