Click here to Skip to main content
13,289,626 members (60,467 online)
Click here to Skip to main content
Add your own
alternative version


373 bookmarked
Posted 19 Oct 2004

Serial Communication using C# and Whidbey

, 20 Oct 2004
Rate this:
Please Sign up or sign in to vote.
In this article, I will give you an introduction on how to do serial port communication on .NET platform using C#.


In this article, I will give you an introduction on how to do serial port communication on .NET platform using C#. The .NET framework version 2.0 (beta) provides features for serial communication. The framework provides System.IO.Ports namespace. The new framework provides classes with the ability to access the serial ports on a computer, and to communicate with serial I/O devices. We will be using RS 232 C standard for communication between PCs. In full duplex mode, here I am not going to use any handshaking or flow control, I will use null modem connection for communication.

The Namespace

The System.IO.Ports namespace contains classes for controlling serial ports. The most important class is the SerialPort class.

The SerialPort Class

SerialPort class provides a framework for synchronous and event-driven I/O, access to pin and break states, and access to serial driver properties. It can be used to wrap Stream objects, allowing the serial port to be accessed by classes that use streams. That is, SerialPort class represents a serial port resource.

Creating SerialPort Object

By creating an object of this type, we will be able to programmatically control all aspects of serial communication.

The methods of SerialPort class that we will use are:

  • ReadLine(): Reads up to the NewLine value in the input buffer. If a New Line is not found before timeout, this method returns a null value.
  • WriteLine(string): Writes the specified string and the New Line value to the output buffer. The written output includes the New Line string.
  • Open(): Opens a new serial port connection.
  • Close(): Closes the port connection.

To create a SerialPort object, all we need to do is:

//create a Serial Port object
SerialPort sp = new SerialPort ();

In all, there are seven public constructors for creating SerialPort. But I am using the parameter less constructor, the constructor uses default property values. For example, the value of DataBits defaults to 8, and StopBits defaults to 1. The default communication port will be COM1.

The public properties of SerialPort class that we will use are:

  • BaudRate: Gets or sets the serial baud rate.
  • StopBits: Gets or sets the standard number of stopbits per byte.
  • ReadTimeout: Gets or sets the number of milliseconds before a timeout occurs when a read operation does not finish.

There are many public properties, but except these three, all properties will have default values.

About Serial Port (Hardware)

The serial port on your PC is a full-duplex device meaning that it can send and receive data at the same time. In order to be able to do this, it uses separate lines for transmitting and receiving data. Some types of serial devices support only one-way communication, and therefore, use only two wires in the cable - the transmit line and the signal ground.

Data Transfer

In serial communication, a byte of data is transferred through a single wire one bit at a time. The packets contain a start bit, data, and stop bit. Once the start bit has been sent, the transmitter sends the actual data bits. There may either be 5, 6, 7, or 8 data bits, depending on the number you have selected. Both receiver and the transmitter must agree on the number of data bits, as well as the baud rate.

Null Modem

A Null Modem cable simply crosses the receive and transmit lines so that transmit on one end is connected to receive on the other end and vice versa. In addition to transmit and receive, DTR & DSR, as well as RTS & CTS are also crossed in a Null Modem connection.

Here is the pin diagram:

Sample screenshot

As we are not using any handshake, we will use three wire connections in which we will connect pin 2 of one connector to pin 3 of the other. For both the connectors, connect pin 5 (ground) of both the connectors with each other (common ground).

If you want, you can use only one PC as both transmitter and receiver for this communication. Then, just take a DB 9 connector and a small wire, and connect pin no 2 and 3 using the wire that will connect a loop back. That is, whatever you will send, the same data you will be receiving.

The Example Application

The main form:

Sample screenshot

Here, if you want to work with default values for the public properties, then press Save Status. If you want to change the value for specified properties, then press Property.

Then the following dialog will pop:

Screenshot - fig2.JPG

Here, you can select values for baud rate and stop bit. To save these changes, press OK.

If you directly press save status or save the changed values for properties, the following form will be displayed:

Sample screenshot

Which will display the values for some of the properties.

For starting communication, press Start Comm. As soon as you press the button, the following form will be displayed:

Screenshot - fig4.JPG

Type data in textbox which is to be transferred, followed by a new line, and press Send button. As soon as you press the button, the data will be send to the send buffer and later to the COM port.

For reading the data form COM port, press Read button. If there is any data in read buffer, it will be displayed in the textbox. If there no data to be read for 500 ms, then an error message will be displayed informing the same.

Here is a code example for the above application:

Code for the Main app

#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Windows.Forms;
using System.IO.Ports;
namespace Serialexpample
    partial class Form1 : Form
        //create instance of property page
        //property page is used to set values for stop bits and 
        //baud rate

        PropertyPage pp = new PropertyPage();

        //create an Serial Port object
        SerialPort sp = new SerialPort();

        public Form1()
        private void propertyButton_Click(object sender, EventArgs e)
            //show property dialog


        private void sendButton_Click(object sender, EventArgs e)
                //write line to serial port
                //clear the text box
                textBox.Text = "";
            catch (System.Exception ex)
                baudRatelLabel.Text = ex.Message;


        private void ReadButton_Click(object sender, EventArgs e)
                //clear the text box
                textBox.Text = "";
                //read serial port and displayed the data in text box
                textBox.Text = sp.ReadLine();
            catch(System.Exception ex)
                baudRatelLabel.Text = ex.Message;

        private void Form1_Load(object sender, EventArgs e)


        private void Form1_FormClosing(object sender, FormClosingEventArgs e)
            MessageBox.Show("Do u want to Close the App");

        private void startCommButton_Click(object sender, EventArgs e)

        //when we want to save the status(value)
        private void saveStatusButton_Click_1(object sender, EventArgs e)
            //display values
            //if no property is set the default values
            if (pp.bRate == "" && pp.sBits == "")
                dataBitLabel.Text = "BaudRate = " + sp.BaudRate.ToString();
                readTimeOutLabel.Text = "StopBits = " + sp.StopBits.ToString();
                dataBitLabel.Text = "BaudRate = " + pp.bRate;
                readTimeOutLabel.Text = "StopBits = " + pp.sBits;

            parityLabel.Text = "DataBits = " + sp.DataBits.ToString();
            stopBitLabel.Text = "Parity = " + sp.Parity.ToString();
            readTimeOutLabel.Text = "ReadTimeout = " + 

            if (propertyButton.Visible == true)

                //open serial port
                //set read time out to 500 ms
                sp.ReadTimeout = 500;
            catch (System.Exception ex)
                baudRatelLabel.Text = ex.Message;

Code for Property Dialog

#region Using directives

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
namespace Serialexpample
    partial class PropertyPage : Form
        //variables for storing values of baud rate and stop bits
        private string baudR="";
        private string stopB="";

        //property for setting and getting baud rate and stop bits
        public string bRate
                return baudR;
                baudR = value;

        public string sBits
                return stopB;
                stopB = value;

        public PropertyPage()

        private void cancelButton_Click(object sender, EventArgs e)
            this.bRate = "";
            this.sBits = "";
            //close form

        private void okButton_Click_1(object sender, EventArgs e)
            //here we set the value for stop bits and baud rate.
            this.bRate = BaudRateComboBox.Text;
            this.sBits = stopBitComboBox.Text;



  • Both receiver and the transmitter must agree on the number of data bits, as well as the baud rate.
  • All the connection for the DB 9 connector should be done accordingly.
  • The article is based on pre-released documentation (.NET Framework 2.0 Beta) and is subject to change in future release.


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


About the Author

Tapan Dantre
Web Developer
India India
No Biography provided

You may also be interested in...

Comments and Discussions

QuestionHow Can we save the data in a text file? Pin
Member 123212704-Apr-16 23:02
memberMember 123212704-Apr-16 23:02 
QuestionCan I get the code for this article? Pin
Member 1232127022-Mar-16 3:04
memberMember 1232127022-Mar-16 3:04 
Questionmay i get the source code? Pin
aminvincent27-Apr-15 1:10
memberaminvincent27-Apr-15 1:10 
QuestionHow can I get source code? Pin
Member 4595213-Jan-14 7:34
memberMember 4595213-Jan-14 7:34 
GeneralMy vote of 1 Pin
ayad0net21-Feb-13 4:40
memberayad0net21-Feb-13 4:40 
SuggestionA simple way to Perform Serial Communication using C# Project Pin
Luzan Baral18-Feb-13 19:05
memberLuzan Baral18-Feb-13 19:05 
Questionan electric pulse of 5 volts to unlock Pin
Thyago Analista29-Jan-13 4:02
memberThyago Analista29-Jan-13 4:02 
AnswerRe: an electric pulse of 5 volts to unlock Pin
roger Palmer22-Apr-14 10:53
memberroger Palmer22-Apr-14 10:53 
QuestionTranslating input data to another custom application. Pin
xp2k2k3sss1-Aug-12 10:23
memberxp2k2k3sss1-Aug-12 10:23 
AnswerRe: Translating input data to another custom application. Pin
Tapan Dantre1-Aug-12 20:25
memberTapan Dantre1-Aug-12 20:25 
GeneralMy vote of 4 Pin
Narendra_uit201023-Mar-12 23:58
memberNarendra_uit201023-Mar-12 23:58 
Questionserial port open Pin
ketakee18-Mar-12 22:57
memberketakee18-Mar-12 22:57 
QuestionHow to show the received signal in Hex? Pin
Member 835129818-Mar-12 7:30
memberMember 835129818-Mar-12 7:30 
GeneralMy vote of 5 Pin
manoj kumar choubey13-Feb-12 1:18
membermanoj kumar choubey13-Feb-12 1:18 
Questionport name Pin
ketakee2-Feb-12 21:24
memberketakee2-Feb-12 21:24 
Questionhow to change the defalut com port com1 to other com7 Pin
satyasankar0931-Jan-12 8:28
membersatyasankar0931-Jan-12 8:28 
Questionhow to scale to simple console application ... Pin
bakrmyounis8-Nov-11 19:06
memberbakrmyounis8-Nov-11 19:06 
AnswerRe: how to scale to simple console application ... Pin
Tapan Dantre9-Nov-11 17:37
memberTapan Dantre9-Nov-11 17:37 
AnswerRe: how to scale to simple console application ... Pin
Member 1119137431-Oct-14 3:23
memberMember 1119137431-Oct-14 3:23 
QuestionSerial port Pin
shivashankar.y.s30-Oct-11 22:59
membershivashankar.y.s30-Oct-11 22:59 
AnswerRe: Serial port Pin
Tapan Dantre31-Oct-11 19:55
memberTapan Dantre31-Oct-11 19:55 
GeneralMy vote of 3 Pin
Habeeballah Hasnoddin13-Jun-11 2:13
memberHabeeballah Hasnoddin13-Jun-11 2:13 
GeneralMy vote of 4 Pin
vikx15-Feb-11 1:50
membervikx15-Feb-11 1:50 
GeneralSerial Port Reading Pin
snevil7-Jan-11 20:58
membersnevil7-Jan-11 20:58 
GeneralAny Serial Port Pin
Orhan Albay21-Oct-10 2:59
memberOrhan Albay21-Oct-10 2:59 
GeneralMy vote of 4 Pin
HimanshuJain13-Oct-10 0:28
memberHimanshuJain13-Oct-10 0:28 
GeneralMy vote of 5 Pin
srinivasks3311-Oct-10 6:23
membersrinivasks3311-Oct-10 6:23 
GeneralMy vote of 1 Pin
Serja Ru9-Jul-10 21:48
memberSerja Ru9-Jul-10 21:48 
GeneralDevice not responding Pin
Riho Pihlak2-Apr-10 14:31
memberRiho Pihlak2-Apr-10 14:31 
Generalprinting problems Pin
yogeshptl14-Dec-09 22:02
memberyogeshptl14-Dec-09 22:02 
GeneralMy vote of 2 Pin
funnydaredevil26-Oct-09 6:28
memberfunnydaredevil26-Oct-09 6:28 
Generalhello, i have a problem reading the COM1 Pin
ablanco934-Sep-09 11:18
memberablanco934-Sep-09 11:18 
AnswerRe: hello, i have a problem reading the COM1 Pin
Tapan Dantre7-Sep-09 22:51
memberTapan Dantre7-Sep-09 22:51 
GeneralRe: hello, i have a problem reading the COM1 Pin
jawed.ace9-Apr-10 9:26
memberjawed.ace9-Apr-10 9:26 
Tapan Dantre thanks for your articles and answer.
i would like to add few point in the above answer.
please check the BaudRate also.
cuz sometimes the device connected through serial port would be having different Baud rate.
i have faced the same issue.then i figured out that the baudrate 9600 is not for my device
then i set it as 115200 and its started communicating through serial port.

General:( program blocking Pin
Member 332072825-Jun-09 2:27
memberMember 332072825-Jun-09 2:27 
AnswerRe: :( program blocking Pin
Tapan Dantre25-Jun-09 2:55
memberTapan Dantre25-Jun-09 2:55 
GeneralRe: :( program blocking Pin
Member 332072825-Jun-09 7:12
memberMember 332072825-Jun-09 7:12 
AnswerRe: :( program blocking Pin
Tapan Dantre25-Jun-09 20:18
memberTapan Dantre25-Jun-09 20:18 
GeneralRe: :( program blocking Pin
Member 332072829-Jun-09 10:15
memberMember 332072829-Jun-09 10:15 
GeneralRe: :( program blocking Pin
Mendor8120-Apr-10 1:10
memberMendor8120-Apr-10 1:10 
QuestionAmount of I/O Reads and I/O Writes in Task Manager is always increased when interacting with SerialPort C# Pin
hungnk19021-Jun-09 19:54
memberhungnk19021-Jun-09 19:54 
QuestionDoes this code works on vista Pin
zakariawaheeb20-Jun-09 6:09
memberzakariawaheeb20-Jun-09 6:09 
AnswerRe: Does this code works on vista Pin
zakariawaheeb20-Jun-09 7:24
memberzakariawaheeb20-Jun-09 7:24 
GeneralProblem receiving data Pin
ConnyP24-Apr-09 9:18
memberConnyP24-Apr-09 9:18 
AnswerRe: Problem receiving data Pin
ConnyP24-Apr-09 9:57
memberConnyP24-Apr-09 9:57 
GeneralSerial port opening- success/failure status Pin
GamePlanner23-Apr-09 14:57
memberGamePlanner23-Apr-09 14:57 
QuestionSerial port busy check Pin
Bronek23-Apr-09 4:26
memberBronek23-Apr-09 4:26 
AnswerRe: Serial port busy check Pin
Mandai10-Jan-10 13:21
memberMandai10-Jan-10 13:21 
GeneralRe: Serial port busy check Pin
Bronek11-Jan-10 11:29
memberBronek11-Jan-10 11:29 
Generalcan't download the source code Pin
pshang16-Jun-11 10:36
memberpshang16-Jun-11 10:36 

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.

Permalink | Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.171207.1 | Last Updated 20 Oct 2004
Article Copyright 2004 by Tapan Dantre
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid