Home > Beginner, C#, Serial Port Series > Serial Port Programming – Part 3 Final Touches and sending data

Serial Port Programming – Part 3 Final Touches and sending data

As always the full program (after the modification discussed here) is in the MSDN Sample Library

There’s a few final touches left and we’ll complete our serial class. Depending on the cabling and the device your serial port is attached to you may require to let it know that your serial port is available for data. We do this by altering our Open method as shown below. Notice lines 18 and 20. DtrEnable is short for Data Terminal Ready and RTS is short for Ready To Send. These settings can (and frequently do) cause an exception depending on if they are supported or not. In my experience those two properties only fail when they’re not needed or if the serial port is not properly initialized. In the example below if the serial port throws an exception it will return false on line 16 and never try to enable DTR/RTS. This is also the reason why nothing is done with the exception.



 1:         public bool Open()
 2:         {
 3:             try
 4:             {
 5:                 this.serialPort.BaudRate = this.baudRate;
 6:                 this.serialPort.DataBits = this.dataBits;
 7:                 this.serialPort.Handshake = this.handshake;
 8:                 this.serialPort.Parity = this.parity;
 9:                 this.serialPort.PortName = this.portName;
 10:                 this.serialPort.StopBits = this.stopBits;
 11:                 this.serialPort.DataReceived += new SerialDataReceivedEventHandler(this._serialPort_DataReceived);
 13:             }
 14:             catch
 15:             { 
 16:                 return false;
 17:             }
 18:             try { serialPort.DtrEnable = true; }
 19:             catch { }
 20:             try { serialPort.RtsEnable = true; }
 21:             catch { }
 23:             return true;
 24:         }


The next step is to add a send method, as show below. You’ll notice that there are two methods, one for string and one for byte[], that just provides flexibility of data input.

 1: public bool Send(byte[] data)
 2:         {
 3:             try
 4:             {
 5:                 serialPort.Write(data, 0, data.Length);
 6:             }
 7:             catch { return false; }
 8:             return true;
 9:         }
 10:         public bool Send(string data)
 11:         {
 12:             try
 13:             {
 14:                 serialPort.Write(data);
 15:             }
 16:             catch { return false; }
 17:             return true;
 18:         }


Next we add an Event for our class to be fired when we have the completed string and if you recall when we received our data we were just writing it out to the console, we instead fire an event with the data. There will be more on creating your own events at a later date. For now here’s the relevent lines of code:

 1:     public delegate void dataReceived(object sender, SerialPortEventArgs arg);
 2:     public class SerialPortEventArgs : EventArgs
 3:     { 
 4:         public string ReceivedData { get; private set; }
 5:         public SerialPortEventArgs(string data)
 6:         {
 7:             ReceivedData = data;
 8:         }
 9:     }

.csharpcode .lnum { color: #606060; }

 51:  // Do something with workingString
 52:    if (this.DataReceived != null)
 53:    {
 54:          SerialPortEventArgs args = new SerialPortEventArgs(workingString);
 55:          this.DataReceived(this, args);
 56:    }

Lastly we add two new textboxes to the form so that we can send and received messages from our serial port and it’s done. It’s that simple to create a serial communicator.

 1:         public Form1()
 2:         {
 3:             InitializeComponent();
 4:             serialPortSettingsControl1.WorkingObject = _workingObject;
 5:             _workingObject.DataReceived += new dataReceived(_workingObject_DataReceived);
 8:         }
 10:         void _workingObject_DataReceived(object sender, SerialPortEventArgs arg)
 11:         {
 12:             this.ReceivedText.Text += arg.ReceivedData;
 13:         }
 14:         private void button3_Click(object sender, EventArgs e)
 15:         {
 16:             _workingObject.Send(this.SendText.Text);
 17:         }


This class can now be pulled into any project along with the control to update the settings and you can quickly implement serial port communications in any project.


  1. Wilfredo Molina
    August 29, 2012 at 2:55 pm

    Hello charpcoder.
    Did you finally finished your serial port programming? I tried to run your program but I don’t see any activity in the Com port. Please, where could we see you final code? Thank you very much, Wilfredo

    • August 29, 2012 at 2:58 pm

      The serial port program should work. Did you download the sample from MSDN Samples? The only thing is it looks for a terminator to the data sent to the serial port, so if you set that right you should get data showing up.

  2. Wilfredo Molina
    August 29, 2012 at 3:13 pm

    Yes. I downloaded your project from http://code.msdn.microsoft.com/SerialPort-brief-Example-ac0d5004. I am using a serial monitor but again, no activity. I am more literate on C++, so please, could you enlighten me more about how to set the terminator? By the way I have set all your default comm parameter but with one stopbit.Thank you, Wilfredo

  3. August 29, 2012 at 3:35 pm

    In SerialPortInterface class there’s a private change the byte below to be what you expect the terminator to be. By default it’s EOT, come to think of it I should’ve used CR:

    /// End of transmition byte in this case EOT (ASCII 4).

    private byte terminator = 0x4;

  4. Wilfredo Molina
    August 29, 2012 at 4:11 pm

    Thank you charpcode for your information. I tried with the terminator but without success. I will be running more tests and keep you posted about it. Regards, Wilfredo

  5. Roberto
    January 23, 2013 at 2:46 pm

    I think there is a bug: in the public bool Open() you have to call this.serialPort.Open(); to open the connection to the port.

    Then it works!

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

%d bloggers like this: