Programming Serial Ports Using Visual Basic 2005

Programming Serial Ports Using Visual Basic 2005

isual Basic programmers who do networking programming will no doubt be familiar with the MSCOMM control in VB6. For those of us who followed VB’s progression to VB.NET, it was a big surprise to find that control missing in .NET 1.x. What we had instead was Platform Invoke (P/Invoke), which was the only way to access the unmanaged Win32 APIs from your managed application. Fortunately, the situation has been rectified: In .NET 2.0, the functionality of the MSCOMM control is restored in the form of the SerialPort control (located under the Components tab in the Toolbox).

In this article, I will show you how to use the SerialPort control in .NET 2.0 for your serial communication needs. In particular, I will build a chat application that allows two computers (connected using either a serial cable or a Bluetooth connection) to communicate. One interesting use of this chat application is in communicating with external serial devices. You will learn how to use the AT commands to programmatically control your mobile phones through a serial Bluetooth connection.

Hardware Needed
Unless you have two computers, you won’t be able to test serial communications. However, you can use a null modem cable to connect two serial ports on the same computer to simulate two computers communicating over serial ports. But most computers today come with at most one serial port (and some notebooks do not even have one). One good solution is to use a USB-to-serial port adapter to convert an USB connection into a serial port. Hence, if you computer does not have any serial ports, you would need a pair of USB-to-serial port adapters, and a null modem cable (see Figure 1). Then, connect each USB-to-serial port adapters to a USB connection.

Figure 1. Accordingly: A USB-to-serial port adapter and a null modem cable will be needed unless you have two serial ports.
Figure 2. Portly: Locate the newly created serial ports and make note of their names; you’ll need them later.

The USB-to-serial port adapter comes with its own drivers. After installing the drivers, right-click on My Computer on the Desktop and select Properties. In the System Properties window, click on the Hardware tab and click the Device Manager button. Expand the Ports (COM & LPT) item and locate the two newly added COM ports (see Figure 2).

On my computer, the two serial ports are COM28 and COM29. Write down the port names as you’ll need these later.

Creating the Chat Application
Using Visual Studio 2005, create a new Windows application and save it as C:SerialCommChat. Populate the default Form1 as shown in Figure 3.

Figure 3. Controlling: Populate the default Form1 with the various controls, as shown in the figure, including buttons, labels, and text box controls.

Set the properties for the various controls as shown in Table 1.

Table 1. Set the properties for the various controls, as shown.


Switch to the Code View for Form1 to start coding the form. First, declare a member variable SerialPort to represent the serial port that you want to work with:

Public Class Form1    Dim WithEvents serialPort As New IO.Ports.SerialPort
Author’s Note: In addition to the SerialPort you can also use the IO.Ports.SerialPort class; both are the same.

Notice that you need to declare SerialPort with the WithEvents keyword. This is because the SerialPort class has the DataReceived event that is fired when data arrives at the serial port and hence you need to service this event to receive the data.

When the form is first loaded, you will retrieve all the available serial port names on your computer using the My.Computer.Ports.SerialPortNames collection and then add these port names to the ComboBox control:

    Private Sub Form1_Load( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles MyBase.Load        For i As Integer = 0 To _           My.Computer.Ports.SerialPortNames.Count - 1            cbbCOMPorts.Items.Add( _               My.Computer.Ports.SerialPortNames(i))        Next        btnDisconnect.Enabled = False    End Sub

Figure 4 shows what the ComboBox control will look like when the form is first loaded.

Figure 4. Port o’ Call: The screen shot shows the ComboBox control displaying all the serial port names.

Once a port name is selected, the user clicks the Connect button to open the selected port. This is accomplished by the following method:

    '-------------------------------------------    ' Event handler for the Connect button    '-------------------------------------------    Private Sub btnConnect_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnConnect.Click        If serialPort.IsOpen Then            serialPort.Close()        End If        Try            With serialPort                .PortName = cbbCOMPorts.Text                .BaudRate = 9600                .Parity = IO.Ports.Parity.None                .DataBits = 8                .StopBits = IO.Ports.StopBits.One            End With            serialPort.Open()            lblMessage.Text = cbbCOMPorts.Text & " connected."            btnConnect.Enabled = False            btnDisconnect.Enabled = True        Catch ex As Exception            MsgBox(ex.ToString)        End Try    End Sub

In particular, notice that I have explicitly set the various properties of the SerialPort class, such as PortName, BaudRate, Parity, etc. These are the communications parameters you need to set when communicating with serial devices. When communicating with serial devices, check their settings such as baudrate, parity, databits, and stopbits and set them accordingly in your application.

The Disconnect button closes the current opened serial port:

    '-------------------------------------------    ' Event handler for the Disconnect button    '-------------------------------------------    Private Sub btnDisconnect_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnDisconnect.Click        Try            serialPort.Close()            lblMessage.Text = serialPort.PortName & " disconnected."            btnConnect.Enabled = True            btnDisconnect.Enabled = False        Catch ex As Exception            MsgBox(ex.ToString)        End Try    End Sub

To send data to the recipient through the serial port, use the Write() method of the SerialPort class:

    '-------------------------------------------    ' Event handler for the Send button    '-------------------------------------------    Private Sub btnSend_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnSend.Click        Try            serialPort.Write(txtDataToSend.Text & vbCrLf)            With txtDataReceived                .SelectionColor = Color.Black                .AppendText(txtDataToSend.Text & vbCrLf)                .ScrollToCaret()            End With            txtDataToSend.Text = String.Empty        Catch ex As Exception            MsgBox(ex.ToString)        End Try    End Sub

One nice feature of the SerialPort class is that you need not constantly poll for incoming data. Instead, you just need to service the DataReceived event and it will automatically fire when incoming data is detected. However, as this event is running on a separate thread, any attempt to update the main Form directly will result in an error. Hence, you need to use a delegate to update controls on the main thread (Form1):

    '-------------------------------------------    ' Event handler for the DataReceived    '-------------------------------------------    Private Sub DataReceived( _       ByVal sender As Object, _       ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _       Handles serialPort.DataReceived        txtDataReceived.Invoke(New _                       myDelegate(AddressOf updateTextBox), _                       New Object() {})    End Sub

The delegate and the updateTextBox() subroutine is defined as follows:

    '------------------------------------------------------    ' Delegate and subroutine to update the Textbox control    '------------------------------------------------------    Public Delegate Sub myDelegate()    Public Sub updateTextBox()        With txtDataReceived            .Font = New Font("Garamond", 12.0!, FontStyle.Bold)            .SelectionColor = Color.Red            .AppendText(serialPort.ReadExisting)            .ScrollToCaret()        End With    End Sub

Testing the Application
You are now ready to test the application. Press F5 in Visual Studio 2005 to debug the application. You need to run another instance of the application in order to test the chat functionality. Hence, go to C:SerialCommChatSerialCommChatinDebug and double-click on SerialCommChat.exe.

In the first instance of the application, select the port number used by your computer for the serial port connection, which you wrote down at the opening of this article. (My computer used port 28.) Then click Connect. On the other instance, select the other port (in my case, port 29) and click Connect. You can now start chatting (see Figure 5)!

Figure 5. Chatty: The application is running, enabling chat between two COM ports.
Figure 6. Turning Japanese: Sending and receiving Japanese characters using the serial port application. .

If you want to converse in other languages (such as Japanese), you need to set the Encoding property of the SerialPort class so that the data can be sent and received correctly:

            With serialPort                .PortName = cbbCOMPorts.Text                .BaudRate = 9600                .Parity = IO.Ports.Parity.None                .DataBits = 8                .StopBits = IO.Ports.StopBits.One                .Encoding = System.Text.Encoding.Unicode            End With

Figure 6 shows sending and receiving Japanese characters.

While I tested the application on my local computer, you can also test the application in the following scenarios:

  • Two computers connected by Bluetooth
  • Two computers connected by a serial cable

Connecting to Serial Devices
One interesting use for the chat application is to communicate with serial devices. One good candidate to test on is your Bluetooth-enabled mobile phone (and modems). Most mobile phones support the AT command set, which means that you can programmatically interact with the phone by issuing AT commands.

To see how our application communicates with a Bluetooth handset, you first need the following hardware:

  • A Bluetooth-enabled handset, such as the Sony Ericsson T68i, or the Motorola E398
  • A Bluetooth adapter for your computer

Before running the application, pair up the computer with the Bluetooth-enabled handset. Your Bluetooth driver (on your computer) will tell you which serial port is being used to connect to the handset. Suppose that COM42 is used to connect to my Sony Ericsson T68i. I will now connect COM42 in my application and then issue the AT command (see Figure 7).

Author’s Note: When communicating with external devices, remember to change the encoding from Unicode to the default.

Figure 7. Here I’m using Bluetooth to issue an AT command to my handset.
Figure 8. Here I’ve added some controls to Form1 in order to provide the user with an interface for manipulating the mobile handset from a computer.

You should see an “AT OK” returned by the phone. You can try out the sample AT commands listed in Table 2.

Table 2. Some AT commands

CommandUsageExample Response
ATAttentionAT OK
AT*List all supported AT commands*EACS*EAID*EALR*EALS*EAM*EAMS*EAPM*EAPNetc
AT+CGMIRequest Manufacturer IdentificationERICSSON
AT+CGMMRequest Model Identification1130202-BVT68
ATDT +NumberDial a number?
AT*EVAAnswer a call?
AT+CBC?Check battery charge+CBC: 0,44 (44 means the battery is 44% charged)
AT+CSQSignal Quality+CSQ: 14,99 (signal strength is from 0 to 31; 14 is the signal strength)

Take note that not all phones support the same AT command set. Refer to your handset’s manual for the AT commands supported.

Two very interesting AT commands are the ATDT and AT*EVA. You can use them to make and receive calls, respectively.

Author’s Note: Not all phones support the above two AT commands. I tested the two commands using the Sony Ericsson T68i.

To allow users to control their mobile phones using their computer, I added the controls as shown in Figure 8.

The code for the Dial Number and Answer Call buttons are as follows:

    '-------------------------------------------    ' Event handler for the Dial Number button    '-------------------------------------------    Private Sub btnDialNumber_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnDialNumber.Click        serialPort.Write("ATDT " & txtPhoneNumber.Text & vbCrLf)    End Sub    '-------------------------------------------    ' Event handler for the Answer Call button    '-------------------------------------------    Private Sub btnAnswerCall_Click( _       ByVal sender As System.Object, _       ByVal e As System.EventArgs) _       Handles btnAnswerCall.Click        serialPort.Write("AT*EVA" & vbCrLf)    End Sub

Press F5 to test the application. You can now enter a phone number, click the Dial Number button, and your mobile phone will automatically dial the number. When the phone rings, click the Answer Call button to answer the call.

As you can see, the SerialPort class has greatly simplified your life by encapsulating much of the functionality that you need (and which are only accessible through P/Invoke in .NET 1.x). Let me know what types of applications you’re able to build using serial communications.


About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist