Working With SerialPort Component in VB.NET
This Blog shows how to use the SerialPort control in .NET 2.0 for the serial communication needs. In particular, it 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. This also explains how to use the AT commands to programmatically control the mobile phones through a serial Bluetooth connection.
This Serialport control was missing in .net 1.0, later microsoft introduced serialport control in .net 2.0 which is very useful control for serial communications and also for file transfering serially using ports and also bluetooth.
Even tough this serialport control and its usage is known to many of them, but of some of them don't know how to use it. Hope this post is very useful to them.
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 . 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 . Then, connect each USB-to-serial port adapters to a USB connection.
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).

Creating a Chat Application:Creating the Chat ApplicationUsing Visual Studio 2005, create a new Windows application and save it as C:\SerialCommChat. Populate the default Form1 as shown in Figure.
Set the properties for the various controls as shown in Table 1.Table 1. Set the properties for the various controls, as shown.
CONTROL PROPERTY VALUE
txtDataReceived Scrollbars Vertical
txtDataToSend Multiline True
txtDataReceived Scrollbars Vertical
txtDataToSend Multiline True
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
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
Public Class Form1
Dim WithEvents serialPort As New IO.Ports.SerialPort
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: shows what the ComboBox control will look like when the form is first loaded.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:\SerialCommChat\SerialCommChat\bin\Debug 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. (Here used port 28.) Then click Connect. On the other instance, select the other port ( port 29) and click Connect. You can now start chatting (see Figure)!
Hope you like this, in my next post I will show how to use serialport for mobile devices.Any feedback on this post is acceptable.
.jpg)
