Sie sind auf Seite 1von 8

13.

1M (42K on) Sign in

articles Q&A forums Lounge Search for articles, questions, tips

Basic serial port listening application


Amund Gjerse, 9 May 2010
4.84 (54 votes) Rate this:

Scans for installed serial ports, queries the supported baud rates, and starts listening to
the selected serial port.

Download source code - 15.2 KB


Download compiled assembly - 7.52 KB
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 nds the installed serial ports. A string array of serial ports is
received through a call made in the constructor of the class SerialPortManager .

Hide Copy Code

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
eld dwSettableBaud from the COMMPROP structure is a join of all supported baud rates.

Hide Copy Code

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:

Hide Copy Code

// 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.

Hide Copy Code

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.

Hide Copy Code


/// 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.

Hide Copy Code

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 les, is licensed under The Code
Project Open License (CPOL)

Share
EMAIL TWITTER

About the Author


Amund Gjerse
Engineer
No Biography provided
Norway

You may also be interested in...


Public, Private, and Hybrid Cloud: What's the Designing For DevOps
difference?

Application to Debug Serial Port Communication A Scalable Path to Commercial IoT Solutions

Serial library for C++ What is Intel Computer Vision SDK?

Comments and Discussions

You must Sign In to use this message board.

Search Go

First Prev Next

Read data via usb port


Member 13154441 27-Apr-17 10:54

Am Using RS 232C Port Weight scale is connecting with my laptop comport. I


thing it's coming Under Com1
Member 13150696 26-Apr-17 2:57

Thank you from the future


Member 12592407 20-Apr-17 9:46
You saved my life
Member 12388252 22-Feb-17 0:13

"dwSettableBaud" and "commProp" ?


YDLU 15-Jul-16 6:08

This just saved me a few hours of work


HoshiKata 13-Jul-16 7:23

Re: This just saved me a few hours of work


Amund Gjerse 2-Aug-16 7:01

Application returns gibberish


yanwang0914 23-Jun-16 5:30

Re: Application returns gibberish


HoshiKata 13-Jul-16 7:20

Cannot receive data from the bluetooth device


Member 12363554 2-Mar-16 22:00

write straight to le
darioits 7-May-15 23:23

how can i send data to serial port using the same program
Sulman Bin Khurshid 1-May-15 0:03

HOw to make this work for multiple COM Ports?


krishnaramu 29-Jan-15 8:05

Application doesn't return data


Member 11280818 10-Jan-15 5:09

Re: Application doesn't return data


john_1726 27-Apr-15 6:18

Re: Application doesn't return data


Member 11640291 12-May-15 13:48

Re: Application doesn't return data


Member 11280818 30-Jul-15 4:39

Program returns (?) question marks.


Member 11067745 8-Sep-14 13:52

Re: Program returns (?) question marks.


Amund Gjerse 8-Sep-14 20:27
Amund Gjerse 8-Sep-14 20:27

Bad zip
Member 10489226 15-May-14 9:16

Re: Bad zip


Amund Gjerse 26-May-14 20:41

Re: Bad zip


balon700 19-Nov-14 11:52

My vote of 1
Member 10698149 6-Apr-14 23:59

Re: My vote of 1
Amund Gjerse 26-May-14 20:43

HELP
LytYrs 12-Feb-14 5:36

Re: HELP
Amund Gjerse 26-May-14 20:45

How to parse string to get $GPGGA?


Taketo Eguchi 28-Nov-13 21:26

Re: How to parse string to get $GPGGA?


Amund Gjerse 28-Nov-13 21:35

Re: How to parse string to get $GPGGA?


Taketo Eguchi 28-Nov-13 21:59

Re: How to parse string to get $GPGGA?


Amund Gjerse 28-Nov-13 22:12

Proper way to catch an unavailable COM port?


Jasper van Stijn 13-Nov-13 11:41

Re: Proper way to catch an unavailable COM port?


Amund Gjerse 28-Nov-13 22:16

time out
Lycian 21-Aug-13 22:25

Re: time out


Amund Gjerse 31-Aug-13 23:41

Das könnte Ihnen auch gefallen