Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Serial Port Programming Part 1 – A (very) brief introduction

, 6 Jan 2012 CPOL
Rate this:
Please Sign up or sign in to vote.
A (very) brief introduction to serial port programming.

My first entry in this blog is going to be about serial ports. Why? Mostly because I read a lot of posts in various programming forums in regards to interacting with the serial ports. Most programmers frequently forget that serial ports have been around a very long time so they act a little different then most current communication technologies.

When deploying an application that will be interacting with serial ports the first question should always be what device will be attached and how? The “how” is the most important question. If the device only uses the transmit, receive and signals ground pins then the deployment is a lot easier, if it use all 8 pins it could increase the complexity of the project.

First some resources, a complete understanding is not really necessary but if you get some of the more challenging devices you might need a detailed understanding of how serial communication works in order to troubleshoot properly. Here’s a short list below:

On to the programming, before proceeding, you might want to have a quick look at the MSDN pages for Serial Port class here.

Below is a very brief implementation of the serial port. There’s more to come however this will get you started. There’s a very important note on this implementation, there must always be a terminator or a set byte length of the data. By set byte length I meant that each block of data that you’ll need to process is x long. So instead of a terminator you use track how many bytes are read to know when you’re received all the data.

Next time – Serial Port Programming Part 2 – Developing a GUI to set the Port Settings and validating the data. 

You can download the code below at http://code.msdn.microsoft.com/SerialPort-brief-Example-ac0d5004.

 1: using System;
 2: using System.IO.Ports;
 3: using System.Text;
 4: 
 5: namespace SerialPortExample
 6: {
 7:     /// <span class="code-SummaryComment"><summary>
</span> 8:     /// Interfaces with a serial port. There should only be one instance
 9:     /// of this class for each serial port to be used.
 10:     /// <span class="code-SummaryComment"></summary>
</span> 11:     public class SerialPortInterface
 12:     {
 13:         private SerialPort  _serialPort     = new SerialPort();
 14:         private int         _baudRate       = 9600;
 15:         private int         _dataBits       = 8;
 16:         private Handshake   _handshake      = Handshake.None;
 17:         private Parity      _parity         = Parity.None;
 18:         private string      _portName       = "COM1";
 19:         private StopBits    _stopBits       = StopBits.One;
 20: 
 21:         /// <span class="code-SummaryComment"><summary>
</span> 22:         /// Holds data received until we get a terminator.
 23:         /// <span class="code-SummaryComment"></summary>
</span> 24:         private string tString              = string.Empty;
 25:         /// <span class="code-SummaryComment"><summary>
</span> 26:         /// End of transmition byte in this case EOT (ASCII 4).
 27:         /// <span class="code-SummaryComment"></summary>
</span> 28:         private byte _terminator            = 0x4;
 29:  
 30:         public int BaudRate         { get { return _baudRate; }     set { _baudRate  = value; } }
 31:         public int DataBits         { get { return _dataBits; }     set { _dataBits  = value; } }
 32:         public Handshake Handshake  { get { return _handshake; }    set { _handshake = value; } }
 33:         public Parity Parity        { get { return _parity; }       set { _parity    = value; } }
 34:         public string PortName      { get { return _portName; }     set { _portName  = value; } }
 35:         public bool Open()
 36:         {
 37:             try
 38:             {
 39:                 _serialPort.BaudRate = _baudRate;
 40:                 _serialPort.DataBits = _dataBits;
 41:                 _serialPort.Handshake = _handshake;
 42:                 _serialPort.Parity = _parity;
 43:                 _serialPort.PortName = _portName;
 44:                 _serialPort.StopBits = _stopBits;
 45:                 _serialPort.DataReceived += 
                         new SerialDataReceivedEventHandler(_serialPort_DataReceived);
 46:             }
 47:             catch { return false; }
 48:             return true;
 49:         }
 50: 
 51:         void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
 52:         {
 53:             //Initialize a buffer to hold the received data
 54:             byte[] buffer = new byte[_serialPort.ReadBufferSize];
 55:  
 56:             //There is no accurate method for checking how many bytes are read
 57:             //unless you check the return from the Read method
 58:             int bytesRead = _serialPort.Read(buffer, 0, buffer.Length);
 59:  
 60:             //For the example assume the data we are received is ASCII data.
 61:             tString += Encoding.ASCII.GetString(buffer, 0, bytesRead);
 62:             //Check if string contains the terminator 
 63:             if (tString.IndexOf((char)_terminator) >

License

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

Share

About the Author

Pantelis Chatzinikolis

United States United States
No Biography provided

Comments and Discussions

 
Questionragarding Comport PinmemberMember 78274723-Mar-13 23:57 
Great Article.
 
is there any specific software available to test the comport programming?
I want PDF Book for port programming to learn in detail,if you know please mail or reply me it's names,and software's name for test comport programs.
 
please, reply me as soon as possible.
 
Thanking you.
GeneralMy vote of 4 PinmemberMember 43208442-Jan-12 10: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 | Terms of Use | Mobile
Web01 | 2.8.1411028.1 | Last Updated 6 Jan 2012
Article Copyright 2011 by Pantelis Chatzinikolis
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid