Click here to Skip to main content
15,884,298 members
Articles / Programming Languages / C#
Article

Testing Serial Application with Virtual Ports

Rate me:
Please Sign up or sign in to vote.
4.53/5 (26 votes)
11 Jul 2008CPOL7 min read 159.8K   7.5K   121   15
Article explains how to install & test virtual ports

Introduction

In this article, we will see how easy it is to test a serial application with virtual port installed on our computer. In addition, I will also walk you through how to install a freely available virtual serial port.

Testing Serial Application

While working in a production environment, many times you might have to create an application that has to communicate to a hardware device through the Serial Port - this port is also called as COM Port / RS-232. In most of the conditions, such application gets data from the serial port which is connected to a hardware device by a serial cable. The data from the device is processed according to the business logic and persistently stored in a database. This stored data might be used to generate graphs, reports, charts and various GUI objects. The challenge to test such an application is if you want to test the data for certain patterns or some special occurrence of characters. In most conditions, you cannot modify the hardware device. To generate the test data, a workaround is needed. You can use a Null Modem Cable that will receive the data from an application like HyperTerminal and transmit it on the other serial port. This implies the condition that you require two serial port sockets on your test PC with a null modem cable. If you don't have either of those, you can use a Virtual Port. In this article, I will describe how to use a virtual port with a C# application.

What is a Null Modem ?

A null modem cable allows you to connect your PC to another PC/serial device using the null modem protocol. With a null modem connection, the transmit and receive lines are cross linked. Connecting two DTE devices together requires a null modem that acts as a DCE between the devices by swapping the corresponding signals (TD-RD, DTR-DSR, and RTS-CTS). This can be done using a wired cable or you can use a Virtual Null Modem which is in fact just a software installed on your computer. There are many advantages of a Virtual Null Modem, you don't need a physical serial cable, your computer's serial cable is free, unlimited number of virtual connections, unlimited distance between the virtual connection.

So now we have decided to use a virtual serial port. Many commercial applications are available. I am using com0com which is a free open source application. com0com comes with a setup ready to install the virtual null model on Windows computer, so if you are just interested in testing an application, you do not need to dig into the C++ code to create a virtual port, although if you are interested in doing research on how to create a virtual port, the code can be found on the sourceforge Web site. The Null-modem emulator (com0com) is an open source kernel-mode virtual serial port driver for Windows, available freely under the GPL license. You can create an unlimited number of virtual COM port pairs and use any pair to connect one application to another. Each pair has two COM ports, the output to one port is the input from the other port and vice versa.

virtualcomport1.JPG

Steps for Installing the Virtual Serial Port

Download the setup file from Sourceforge, copy the file on the hard drive. First you need to unzip the file to a folder. In the folder, you will find setup.exe. Install it on your computer. Follow this step by step process:

  1. Open the folder where you had extracted the zip file and click on the file named as Setup.exe, optionally you can go through the ReadMe.txt file - the setup instructions are provided in it. 
  2. A screen saying "Welcome to the Null-modem emulator ( com0com) Setup wizard" will open. Click on Next button.
  3. You will see the "License Agreement". Click on I Agree button.
  4. You will see the "Choose Component" screen, just click Next button.
  5. "Choose Install Location". I left it as default. You can make your choice and click Install button.
  6. A console prompt might pop-up during the installation. Don't worry, just let it do its work.
  7. Twice you will get the "Install the software automatically (Recommended)", click Next for both.

Now the Installation of the Null-Modem emulator is complete. You can go to the Start Menu and find in the program's folder a directory com0com, which has a link named as "Setup" with a null-modem icon on it. Click the link and the application will be visible. Now in order to use this null modem in our C# Windows application, we need to change the names of the port. This is very important as the .NET Framework uses the System.IO.Ports to access the COM ports. A function named as serialPort1.Open() is used to open a connection, but it only lets you use a port whose name starts with COM, don't know why Microsoft selected to do so. The bottom line is if you want to use System.IO.Ports, you need to name your COM ports starting with COM. To change the name of the ports, maximize the window "Setup for com0com", edit the textbox displaying the name of the ports and then click on Apply. For our application, let us change the name as COMA and COMB . It will take a while for the application to make the change. You will see the famous hourglass icon for some time.

Once you have configured the default ports, you can add more pairs of ports if you like. Just be sure to change the port name starting with COM. For each pair of ports you add, you should get a 'Found New Hardware Wizard' for each individual port. Once the port is added, you will view the ports populated in the Tree View on the Left hand corner.

Use Hyper Terminal To Test Virtual Ports

For testing, our virtual port has been setup properly. Let's use the popular Hyper Terminal. To start an instance of hyper terminal, go to Windows Start Menu->Programs -> Accessories -> Communication -> Hyperterminal.

  • Create connection for COMA
  • Open the File Menu -> New Connection
  • Enter a name, say Test_COMA, choose the icon and press Ok button
  • Select from the dropdown list COMA, press OK button
  • Keep the properties default and press OK button
  • Create connection for COMB
  • Open the File Menu -> New Connection
  • Enter a name, say Test_COMB, choose the icon and press Ok button
  • Select from the dropdown list COMB, press OK button
  • Keep the properties default and press OK button

You can now test the Null Modem by typing in the white text area of COMA, you should see the data appear on the screen of COMB, thus the data is transmitted successfully from COMA to COMB.

Let's Create Our Serial Port Application using C#

Go to your Visual Studio Editor and create a new project or you can download the code sample I have uploaded. I am using Visual Studio 2005. You might have a different version but more or less the process remains the same. To create the project, click on File -> New -> Project, the new project dialogbox will open (as shown in the image below). Type in the project name as “VirtualCom” select the location and click Ok . Double click on the "Form1" to open it in the design view, expand the Toolbox menu on the left side of the Visual Studio, drag and drop the Serial Port control on the form, open the properties of the Serial Port control, change the name of the control to ‘COMA‘, ensure the Baud Rate is 9600, Data bits ‘8’, parity ‘None’, Stop bits 1, or all same as you set in the Hyper terminal . Drag and drop two textbox names, one as “txtReceive” and the other as “txtSend”, also put a command button and name it as “btnSend”.

vsharpproject.jpg

Copy the code below in your form1.cs. Before you debug / run the application, only one hyper terminal needs to be active the one with COMB. Close Hyper terminal for COMA, because if it is active and connected then the C# application will not be able to open the port and will throw an exception, so ensure you have disconnected the hyper terminal for COMA and kept alive only the Hyper terminal window for COMB, also ensure proper Flow Control. Run the application and click on the command button  you should see "WELCOME"  in the hyperterminal, type some data in the hyperterminal and that should be displayed in the Textbox.  

C++
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;

namespace VirtualCom
{
    public partial class frmVirtualCom : Form
    {
        public frmVirtualCom()
        {
            InitializeComponent();
            // Open the Serial port, if not already opened
            // put a try catch to catch if Open() throws an exception
            if (!serialPort1.IsOpen)
            {
                try
                {
                    serialPort1.Open();
                }
                catch (System.Exception ex)
                {
                    MessageBox.Show(ex.ToString());
                }
            }
        }

delegate void OutputUpdateDelegate(string data);
private void OutputUpdateCallback(string data)
 {
     txtReceive.Text += data;
 }

        private void DataRec
		(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
        {
            try
            {
                string data = serialPort1.ReadExisting();
                //txtreceive.Text += data;     
                //Not good as Serialport is a different Thread
                //OutputUpdateCallback(data);  //call directly will not work

                //You need to use the Invoke Method and pass the delegate and data
                txtReceive.Invoke(new OutputUpdateDelegate(OutputUpdateCallback),data);
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }

        private void btnSend_Click(object sender, EventArgs e)
        {
            try
            {
                serialPort1.Write("WELCOME ");
            }
            catch (System.Exception ex)
            {
                MessageBox.Show(ex.ToString());
            }
        }
    }
}

Points of Interest

You can read more on MSDN for Serial Device and Drivers for Windows here.

History

  • 11th July, 2008: Article created

License

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


Written By
Software Developer (Senior)
India India
My name is Vikas Amin ,my childhood dream was to be a rocket scientist so many times ended with burned hand meshing with firecracker rockets. Now I mesh with computer's using C#,VC++,C,C++,VB,ASP,Silverlight,WPF,WCF,Assebly language some vbscript and javascript.

Comments and Discussions

 
BugNot Working Pin
Ravikumargn23-May-16 23:05
Ravikumargn23-May-16 23:05 
QuestionHow about an update to this article? Pin
MatthysDT10-Aug-15 23:16
MatthysDT10-Aug-15 23:16 
Questionhow in wpf? Pin
cppwxwidgetsss2-Dec-09 2:18
cppwxwidgetsss2-Dec-09 2:18 
Generalgood job Pin
cppwxwidgetsss1-Dec-09 21:25
cppwxwidgetsss1-Dec-09 21:25 
GeneralNice! Pin
alrsds17-Sep-09 18:12
alrsds17-Sep-09 18:12 
GeneralRe: Nice! Pin
vikas amin18-Sep-09 15:40
vikas amin18-Sep-09 15:40 
GeneralMy vote of 1 Pin
mohammad_esmaili26-Dec-08 20:16
mohammad_esmaili26-Dec-08 20:16 
GeneralI need help :-( Pin
Stephanie Boldt27-Jul-08 23:34
Stephanie Boldt27-Jul-08 23:34 
GeneralRe: I need help :-( Pin
vikas amin28-Jul-08 6:35
vikas amin28-Jul-08 6:35 
What I understand is ,
you have a c# application that has to communicate to a Map application ,both are connected to a serial port COM50 and COM60 respectively . Now your c# application needs to know if the map application is ready or not ??So you open the port COM60 in your map application and check by IsOpen.

If the above is right :-
The IsOpen property tracks whether the port is open for use by the caller (c# application), not whether the port is open by any application on the machine (Map application).
If you need to know if the port is open by other application, you can use the exception handling mechanism < which i have used in my article >

try
{
serialPort1.Open();
}
catch (System.Exception ex)
{
MessageBox.Show(ex.ToString());
}

If port is open ideally you should get System.InvalidOperationException but you can also get System.UnauthorizedAccessException . So if your code reaches inside the catch block your port is open on machine else the port is close. I recommand to check System.Exception while opening the port.

Also a general suggestion for your application is the ideal way to check if the Map Application has process the data is to get a acknowlegement back from the map app.

Vikas Amin

My First Article on CP" Virtual Serail Port "[^]
modified on Thursday, July 24, 2008 5:33 PM

GeneralRe: I need help :-( Pin
Iain Clarke, Warrior Programmer30-Jul-08 4:44
Iain Clarke, Warrior Programmer30-Jul-08 4:44 
GeneralXP, Vista Pin
Luc Pattyn11-Jul-08 12:45
sitebuilderLuc Pattyn11-Jul-08 12:45 
GeneralRe: XP, Vista Pin
Ed.Poore14-Jul-08 1:39
Ed.Poore14-Jul-08 1:39 
GeneralRe: XP, Vista Pin
Luc Pattyn14-Jul-08 1:49
sitebuilderLuc Pattyn14-Jul-08 1:49 
GeneralRe: XP, Vista Pin
Ed.Poore14-Jul-08 2:03
Ed.Poore14-Jul-08 2:03 
GeneralRe: XP, Vista Pin
vikas amin14-Jul-08 4:33
vikas amin14-Jul-08 4:33 

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.