Click here to Skip to main content
15,885,216 members
Articles / Programming Languages / C#

Serial Port Programming Part 1 – A (Very) Brief Introduction

Rate me:
Please Sign up or sign in to vote.
4.80/5 (5 votes)
6 Jan 2012CPOL2 min read 42.9K   44   2
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 with 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 than 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 uses 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.

C#
1: using System;
2: using System.IO.Ports;
3: using System.Text;
4:
5: namespace SerialPortExample
6: {
7:     /// <summary>
8:     /// Interfaces with a serial port. There should only be one instance
9:     /// of this class for each serial port to be used.
10:     /// </summary>
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:         /// <summary>
22:         /// Holds data received until we get a terminator.
23:         /// </summary>
24:         private string tString              = string.Empty;
25:         /// <summary>
26:         /// End of transmition byte in this case EOT (ASCII 4).
27:         /// </summary>
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) > -1)
64:             {
65:                 //If tString does contain terminator we
                    //cannot assume that it is the last character received
66:                 string workingString = tString.Substring(0, tString.IndexOf((char)_terminator));
67:                 //Remove the data up to the terminator from tString
68:                 tString = tString.Substring(tString.IndexOf((char)_terminator));
69:                 //Do something with workingString
70:                 Console.WriteLine(workingString);
71:             }
72:         }
73:
74:     }
75: }

License

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


Written By
United States United States
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
Questionragarding Comport Pin
Member 78274723-Mar-13 22:57
Member 78274723-Mar-13 22:57 
GeneralMy vote of 4 Pin
Member 43208442-Jan-12 9:28
Member 43208442-Jan-12 9:28 

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.