Click here to Skip to main content
Click here to Skip to main content

Serial Port Communication

, 8 Apr 2012
Rate this:
Please Sign up or sign in to vote.
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:

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

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

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.

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.

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.

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.  

this.Invoke(new EventHandler(DisplayText));

The below DisplayText method is called  by the invoke method.

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

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

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)

About the Author

Sreedeep.S
Student
India India
No Biography provided

Comments and Discussions

 
QuestionHow can I get source code? PinmemberMember 4595213-Jan-14 6:29 
Questionweird characters PinmemberDoğan Etkin Irmaklı9-Oct-13 4:14 
Questionwhat if the data with header and footer Pinmembergambrenk17-Sep-13 5:43 
QuestionRFID WRITE PinmemberPradeep.1july8-May-12 15:54 
SuggestionRe: RFID WRITE PinmemberSreedeep.S10-May-12 22:25 
QuestionHow can I get source code? PinmemberMember 4595213-Jan-14 6:28 

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

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

| Advertise | Privacy | Mobile
Web04 | 2.8.140721.1 | Last Updated 8 Apr 2012
Article Copyright 2012 by Sreedeep.S
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid