Click here to Skip to main content
12,696,092 members (30,495 online)
Click here to Skip to main content
Add your own
alternative version


131 bookmarked

Basic serial port listening application

, 9 May 2010 CPOL
Rate this:
Please Sign up or sign in to vote.
Scans for installed serial ports, queries the supported baud rates, and starts listening to the selected serial port.



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.

public SerialPortManager()
    // Finding installed serial ports on hardware
    _currentSerialSettings.PortNameCollection = 
    _currentSerialSettings.PropertyChanged += 
                       new System.ComponentModel.PropertyChangedEventHandler

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

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.

private void UpdateBaudRateCollection()
    _serialPort = new SerialPort(_currentSerialSettings.PortName);

    // 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);


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:

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

    // Setting serial port settings
    _serialPort = new SerialPort(

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

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.

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

/// Closes the serial port
public void StopListening()

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

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 });


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


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


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


About the Author

Amund Gjersøe
Norway Norway
No Biography provided

You may also be interested in...


Comments and Discussions

Question"dwSettableBaud" and "commProp" ? Pin
YDLU15-Jul-16 7:08
memberYDLU15-Jul-16 7:08 
PraiseThis just saved me a few hours of work Pin
HoshiKata13-Jul-16 8:23
memberHoshiKata13-Jul-16 8:23 
PraiseRe: This just saved me a few hours of work Pin
Amund Gjersøe2-Aug-16 8:01
memberAmund Gjersøe2-Aug-16 8:01 
QuestionApplication returns gibberish Pin
yanwang091423-Jun-16 6:30
memberyanwang091423-Jun-16 6:30 
AnswerRe: Application returns gibberish Pin
HoshiKata13-Jul-16 8:20
memberHoshiKata13-Jul-16 8:20 
QuestionCannot receive data from the bluetooth device Pin
Member 123635542-Mar-16 23:00
memberMember 123635542-Mar-16 23:00 
Questionwrite straight to file Pin
darioits8-May-15 0:23
memberdarioits8-May-15 0:23 
Questionhow can i send data to serial port using the same program Pin
Sulman Bin Khurshid1-May-15 1:03
memberSulman Bin Khurshid1-May-15 1:03 
QuestionHOw to make this work for multiple COM Ports? Pin
krishnaramu29-Jan-15 9:05
memberkrishnaramu29-Jan-15 9:05 
QuestionApplication doesn't return data Pin
Member 1128081810-Jan-15 6:09
memberMember 1128081810-Jan-15 6:09 
AnswerRe: Application doesn't return data Pin
john_172627-Apr-15 7:18
memberjohn_172627-Apr-15 7:18 
GeneralRe: Application doesn't return data Pin
Member 1164029112-May-15 14:48
memberMember 1164029112-May-15 14:48 
QuestionRe: Application doesn't return data Pin
Member 1128081830-Jul-15 5:39
memberMember 1128081830-Jul-15 5:39 
QuestionProgram returns (?) question marks. Pin
Member 110677458-Sep-14 14:52
memberMember 110677458-Sep-14 14:52 
AnswerRe: Program returns (?) question marks. Pin
Amund Gjersøe8-Sep-14 21:27
memberAmund Gjersøe8-Sep-14 21:27 
QuestionBad zip Pin
Member 1048922615-May-14 10:16
memberMember 1048922615-May-14 10:16 
AnswerRe: Bad zip Pin
Amund Gjersøe26-May-14 21:41
memberAmund Gjersøe26-May-14 21:41 
AnswerRe: Bad zip Pin
balon70019-Nov-14 12:52
memberbalon70019-Nov-14 12:52 
GeneralMy vote of 1 Pin
Member 106981497-Apr-14 0:59
memberMember 106981497-Apr-14 0:59 
GeneralRe: My vote of 1 Pin
Amund Gjersøe26-May-14 21:43
memberAmund Gjersøe26-May-14 21:43 
QuestionHELP Pin
LytYrs12-Feb-14 6:36
memberLytYrs12-Feb-14 6:36 
AnswerRe: HELP Pin
Amund Gjersøe26-May-14 21:45
memberAmund Gjersøe26-May-14 21:45 
QuestionHow to parse string to get $GPGGA? Pin
Taketo Eguchi28-Nov-13 22:26
memberTaketo Eguchi28-Nov-13 22:26 
AnswerRe: How to parse string to get $GPGGA? Pin
Amund Gjersøe28-Nov-13 22:35
memberAmund Gjersøe28-Nov-13 22:35 
GeneralRe: How to parse string to get $GPGGA? Pin
Taketo Eguchi28-Nov-13 22:59
memberTaketo Eguchi28-Nov-13 22:59 
GeneralRe: How to parse string to get $GPGGA? Pin
Amund Gjersøe28-Nov-13 23:12
memberAmund Gjersøe28-Nov-13 23:12 
QuestionProper way to catch an unavailable COM port? Pin
Jasper van Stijn13-Nov-13 12:41
memberJasper van Stijn13-Nov-13 12:41 
AnswerRe: Proper way to catch an unavailable COM port? Pin
Amund Gjersøe28-Nov-13 23:16
memberAmund Gjersøe28-Nov-13 23:16 
Questiontime out Pin
Lycian21-Aug-13 23:25
memberLycian21-Aug-13 23:25 
AnswerRe: time out Pin
Amund Gjersøe1-Sep-13 0:41
memberAmund Gjersøe1-Sep-13 0:41 
QuestionDiscrete values Pin
CatOfTheCanals2-Jul-13 4:03
memberCatOfTheCanals2-Jul-13 4:03 
AnswerRe: Discrete values Pin
Amund Gjersøe2-Jul-13 4:21
memberAmund Gjersøe2-Jul-13 4:21 
GeneralRe: Discrete values Pin
CatOfTheCanals2-Jul-13 23:30
memberCatOfTheCanals2-Jul-13 23:30 
GeneralMy vote of 4 Pin
hamid.mousavinasab26-Mar-13 3:21
memberhamid.mousavinasab26-Mar-13 3:21 
GeneralMy vote of 1 Pin
Member 993964224-Mar-13 23:58
memberMember 993964224-Mar-13 23:58 
GeneralRe: My vote of 1 Pin
Amund Gjersøe25-Mar-13 0:32
memberAmund Gjersøe25-Mar-13 0:32 
QuestionWriting to the serial port Pin
vasch2-Jan-13 4:33
membervasch2-Jan-13 4:33 
QuestionGood Application: Do you have the MVC 3 application for this? Pin
matimu ngobeni18-Nov-12 22:45
membermatimu ngobeni18-Nov-12 22:45 
Thanks for my vote is 4

i tested the application and is working well.

i am doing a alcohol sensor and gps application and i need to make it a WEB based app (mostly MVC)

any help or ideas

QuestionTesting Serial Listener ? Pin
ZARk_be26-Sep-12 1:16
memberZARk_be26-Sep-12 1:16 
AnswerRe: Testing Serial Listener ? Pin
Amund Gjersøe26-Sep-12 1:24
memberAmund Gjersøe26-Sep-12 1:24 
QuestionBinary Data Parse Pin
Embedded Planet17-Jul-12 12:22
memberEmbedded Planet17-Jul-12 12:22 
GeneralRe: Binary Data Parse Pin
Amund Gjersøe30-Jul-12 2:47
memberAmund Gjersøe30-Jul-12 2:47 
Generalis there any other serial port like articles? Pin
lyglary9-Jul-12 23:51
memberlyglary9-Jul-12 23:51 
Generalhi...Thank yu for saving my day Pin
dombanyasha7-Jun-12 11:09
memberdombanyasha7-Jun-12 11:09 
QuestionThanx Pin
dombanyasha7-Jun-12 11:08
memberdombanyasha7-Jun-12 11:08 
QuestionThanks , Just what I was searching for , BUT, Pin
Member 228177127-Nov-10 8:45
memberMember 228177127-Nov-10 8:45 
AnswerRe: Thanks , Just what I was searching for , BUT, Pin
Amund9-Dec-10 2:38
memberAmund9-Dec-10 2:38 
GeneralProblem to get the Baudrate Pin
NMehta8317-Nov-10 20:21
memberNMehta8317-Nov-10 20:21 
GeneralRe: Problem to get the Baudrate Pin
Amund18-Nov-10 22:53
memberAmund18-Nov-10 22:53 
QuestionCan't open port COM1? Pin
Jun Du22-Jul-10 5:26
memberJun Du22-Jul-10 5:26 

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.

| Advertise | Privacy | Terms of Use | Mobile
Web02 | 2.8.170118.1 | Last Updated 10 May 2010
Article Copyright 2010 by Amund Gjersøe
Everything else Copyright © CodeProject, 1999-2017
Layout: fixed | fluid