Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / desktop / WinForms

Serial Port Communication

4.50/5 (16 votes)
8 Apr 2012CPOL2 min read 157.3K  
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)