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

Serial Port Programming – Part 3: Final touches and sending data

Rate me:
Please Sign up or sign in to vote.
4.50/5 (2 votes)
31 Dec 2011CPOL2 min read 28.4K   18   2
This class can be pulled into any project along with the control to update the settings and you can quickly implement serial port communications in any project.

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

There’re 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.

C#
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);
12:
13:             }
14:             catch
15:             {
16:                 return false;
17:             }
18:             try { serialPort.DtrEnable = true; }
19:             catch { }
20:             try { serialPort.RtsEnable = true; }
21:             catch { }
22:
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.

C#
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 relevant lines of code:

C#
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:     }
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.

C#
1:         public Form1()
2:         {
3:             InitializeComponent();
4:             serialPortSettingsControl1.WorkingObject = _workingObject;
5:             _workingObject.DataReceived += new dataReceived(_workingObject_DataReceived);
6:
7:
8:         }
9:
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.

Serialportsample

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

 
GeneralMy vote of 5 Pin
Member 43208442-Jan-12 9:36
Member 43208442-Jan-12 9:36 
GeneralRe: My vote of 5 Pin
poorfool919-Mar-14 18:28
poorfool919-Mar-14 18: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.