Click here to Skip to main content
15,881,248 members
Articles / Programming Languages / C# 4.0

Basic serial port listening application

Rate me:
Please Sign up or sign in to vote.
4.87/5 (69 votes)
9 May 2010CPOL2 min read 538.8K   81.5K   153   79
Scans for installed serial ports, queries the supported baud rates, and starts listening to the selected serial port.

SerialPortListenerApp

Introduction

This is a basic sample of serial port (COM port) listening in C#. This application is connected to a GPS sending ASCII text for test, but the serial port listening part is all byte-oriented.

CodeProject is missing a simple serial port application. Serial port listening applications usually have this only as a part of a bigger solution, while this application does nothing else than list the available COM-ports, list the available baud rates for the selected COM-port, and starts sending the data. In this solution, a form converts the data to ASCII-text and displays it in a text box.

Using the code

The serial port handling code is placed in a class called SerialPortManager. This class contains methods to start and stop listening for data on the serial port.

Finding the installed serial ports

Rather than just assuming the number of serial ports, or leaving it up to the user to know this beforehand, the code finds the installed serial ports. A string array of serial ports is received through a call made in the constructor of the class SerialPortManager.

C#
public SerialPortManager()
{
    // Finding installed serial ports on hardware
    _currentSerialSettings.PortNameCollection = 
            System.IO.Ports.SerialPort.GetPortNames();
    _currentSerialSettings.PropertyChanged += 
                       new System.ComponentModel.PropertyChangedEventHandler
                       (_currentSerialSettings_PropertyChanged);

    // If serial ports is found, we select the first found
    if (_currentSerialSettings.PortNameCollection.Length > 0)
        _currentSerialSettings.PortName = 
             _currentSerialSettings.PortNameCollection[0];
}

Updating baud rates supported by the selected device

When a serial port is selected by the user, a query for supported baud rates is done. Depending on the hardware, different collections of baud rates may be supported. The field dwSettableBaud from the COMMPROP structure is a join of all supported baud rates.

C#
private void UpdateBaudRateCollection()
{
    _serialPort = new SerialPort(_currentSerialSettings.PortName);
    _serialPort.Open();

    // Getting COMMPROP structure, and its property dwSettableBaud.
    object p = _serialPort.BaseStream.GetType().GetField("commProp", 
       BindingFlags.Instance | BindingFlags.NonPublic).GetValue(_serialPort.BaseStream);
    Int32 dwSettableBaud = (Int32)p.GetType().GetField("dwSettableBaud", 
       BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public).GetValue(p);

    _serialPort.Close();
    _currentSerialSettings.UpdateBaudRateCollection(dwSettableBaud);
}

Serial port settings

The class named SerialSettings contains the currently selected serial port settings, and also includes lists of alternatives for the different setting properties. Everything is data bound to the GUI.

Start listening to a serial port

The serial port is instantiated using the currently selected settings:

C#
// Connects to a serial port defined through the current settings
public void StartListening()
{
    // Closing serial port if it is open
    if (_serialPort != null && _serialPort.IsOpen)
        _serialPort.Close();

    // Setting serial port settings
    _serialPort = new SerialPort(
        _currentSerialSettings.PortName,
        _currentSerialSettings.BaudRate,
        _currentSerialSettings.Parity,
        _currentSerialSettings.DataBits,
        _currentSerialSettings.StopBits);

     // Subscribe to event and open serial port for data
     _serialPort.DataReceived += 
         new SerialDataReceivedEventHandler(_serialPort_DataReceived);
     _serialPort.Open();
}

The actual serial port reading

The actual serial port reading runs in a threadpool. When data is received on the serial port, an event is raised and _serialPort_DataReceived is called.

C#
void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    int dataLength = _serialPort.BytesToRead;
    byte[] data = new byte[dataLength];
    int nbrDataRead = _serialPort.Read(data, 0, dataLength);
    if (nbrDataRead == 0)
        return;
          
    // Send data to whom ever interested
    if (NewSerialDataRecieved != null)
        NewSerialDataRecieved(this, new SerialDataEventArgs(data));
}

The received byte array is sent to those listening for the event. The class SerialDataEventArgs houses a byte array.

Stop listening

We stop listening by simply closing the serial port. Note that this might deadlock your UI-thread if you are using Invoke in the event handling in your form.

C#
/// Closes the serial port
public void StopListening()
{
     _serialPort.Close();
}

To work around this possible deadlock, a BeginInvoke is needed. And, that is generally good practice as well.

C#
if (this.InvokeRequired)
{
    // Using this.Invoke causes deadlock when closing serial port,
    // and BeginInvoke is good practice anyway.
    this.BeginInvoke(new EventHandler<SerialDataEventArgs>(
       _spManager_NewSerialDataRecieved), new object[] { sender, e });
    return;
}

Summary

A rather simple sample in how to implement serial port listening has been provided.

Updates

  • 27 April 2010 - Code clean-up and getting < > to show in the article.
  • 10 May 2010 - Fixing some misspells in the article.

License

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


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

Comments and Discussions

 
QuestionWhich Statement to Display the Receiving data in Textbox Pin
Member 154521843-Dec-21 0:24
Member 154521843-Dec-21 0:24 
QuestionProblem WIndows 11 Pin
Tomáš Pokorný1-Nov-21 2:28
Tomáš Pokorný1-Nov-21 2:28 
QuestionHow did u put values to text box Pin
elephant12365478913-Sep-21 3:25
elephant12365478913-Sep-21 3:25 
QuestionAdd code to display non-printable character Pin
unolegg11-Jul-21 12:52
unolegg11-Jul-21 12:52 
QuestionBinary Data Parse Pin
Piotr669-Oct-20 11:47
Piotr669-Oct-20 11:47 
AnswerRe: Binary Data Parse Pin
Member 1515205217-Jun-21 6:39
Member 1515205217-Jun-21 6:39 
GeneralMy vote of 5 Pin
Member 1219951431-Aug-20 9:52
Member 1219951431-Aug-20 9:52 
QuestionVote of 5 Pin
Steve Hageman10-Dec-19 17:42
Steve Hageman10-Dec-19 17:42 
GeneralMy vote of 5 Pin
uhoh2111-Oct-19 21:07
uhoh2111-Oct-19 21:07 
QuestionVery Nice, but how to read data from multiple com ports in single window in single time Pin
Member 1192794213-May-19 0:39
Member 1192794213-May-19 0:39 
PraiseUltimate Solution Pin
Santosh Biradar15-Mar-18 1:00
Santosh Biradar15-Mar-18 1:00 
Questionspliting str string Pin
sagram00017-Dec-17 9:53
sagram00017-Dec-17 9:53 
QuestionRead data via usb port Pin
Nykhael27-Apr-17 10:54
Nykhael27-Apr-17 10:54 
QuestionAm Using RS 232C Port Weight scale is connecting with my laptop comport. I thing it's coming Under Com1 Pin
Member 1315069626-Apr-17 2:57
Member 1315069626-Apr-17 2:57 
PraiseThank you from the future Pin
Member 1259240720-Apr-17 9:46
Member 1259240720-Apr-17 9:46 
QuestionYou saved my life Pin
Member 1238825222-Feb-17 0:13
Member 1238825222-Feb-17 0:13 
Question"dwSettableBaud" and "commProp" ? Pin
YDLU15-Jul-16 6:08
YDLU15-Jul-16 6:08 
PraiseThis just saved me a few hours of work Pin
HoshiKata13-Jul-16 7:23
HoshiKata13-Jul-16 7:23 
PraiseRe: This just saved me a few hours of work Pin
Amund Gjersøe2-Aug-16 7:01
Amund Gjersøe2-Aug-16 7:01 
QuestionApplication returns gibberish Pin
yanwang091423-Jun-16 5:30
yanwang091423-Jun-16 5:30 
AnswerRe: Application returns gibberish Pin
HoshiKata13-Jul-16 7:20
HoshiKata13-Jul-16 7:20 
QuestionCannot receive data from the bluetooth device Pin
Member 123635542-Mar-16 22:00
Member 123635542-Mar-16 22:00 
Questionwrite straight to file Pin
darioits7-May-15 23:23
darioits7-May-15 23:23 
Questionhow can i send data to serial port using the same program Pin
Sulman Bin Khurshid1-May-15 0:03
Sulman Bin Khurshid1-May-15 0:03 
QuestionHOw to make this work for multiple COM Ports? Pin
krishnaramu29-Jan-15 8:05
krishnaramu29-Jan-15 8:05 

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.