Click here to Skip to main content
15,881,204 members
Articles / Programming Languages / Visual Basic

Asynchronous Serial Port Communication

Rate me:
Please Sign up or sign in to vote.
2.20/5 (16 votes)
21 Apr 2008CPOL2 min read 68.1K   28   32   8
How to communicate to a serial port asynchronously

Introduction

It's been a while since I was looking for a way of communication with my custom device which has a port for the communication. I was looking an asynchronous method because the serial port can receive data from the device at any point of time.

Background

The idea behind the code was that any time the serial port receives any data, an event will fire from the port class, i.e. DataReceived. This event helps to detect any data received to the serial port at any point of time and it's very helpful. To make it more helpful, I have created a simple class which helps to create a connection with the serial port easily and instantly. Here is the class diagram which will help you to understand it.

AsyncSerilPort

Using the Code

The name of the class is ASYNCSERIALPORT. Create an instance of a class on any form or other class. While creating the instance, you can pass the parameter required for the connection. The parameters are optional. The only parameter required is the port name.

VB.NET
    ''Creating the Instance of the Class
Dim NewAsyncSerialPort As New AsyncSerialPort("COM1")

Or:

VB.NET
 ''Creating the Instance of the Class
Dim NewAsyncSerialPort As New AsyncSerialPort("COM1", 9600, _
                               IO.Ports.Parity.None, 8, IO.Ports.StopBits.One)

The other parameters are BaudRate, Parity, DataBits and Stopbits.

Sending Data to the Serial Port

To send the data, you need to call the sub to do so. Let's take a look at the sub:

VB.NET
''Private Sub for sending Data. You may change to Public if needed.
Private Sub SendByte(ByVal byts() As Byte)
If Port.IsOpen = False Then
    Port.Open()
End If
Port.Write(byts, 0, byts.Length)
End Sub

You need to pass an array of bytes, array of char or a string to send data.

Receiving Data from the Serial Port

To receive data from the serial port, we will use the event of the IO.Ports.SerialPort. So declare the port with events:

VB.NET
Private WithEvents Port As IO.Ports.SerialPort

Now, we will create a sub which will handle the event when the data is received:

VB.NET
Private Sub ReceivedBytes(ByVal sender As Object, _
    ByVal e As IO.Ports.SerialDataReceivedEventArgs) Handles Port.DataReceived
    BufferSize = Port.BytesToRead
    TotalByteLastRec = TotalByteLastRec + BufferSize
    If BufferSize > 0 Then
        Port.Read(InBuffer, LastOffset, BufferSize)
        '' Some useful code to process the data
        LastOffset = BufferSize
    End If
     LastOffset = 0
    BufferSize = 0
    Port.DiscardInBuffer()
End Sub

This sub will handle the event whenever a port receives any data.

Couple of Properties within the Class

VB.NET
Public ReadOnly Property CurrentBufferSize() As Integer
    Get
        Return BufferSize
    End Get
End Property
Public ReadOnly Property TotalBytesReceived() As Integer
    Get
        Return TotalByteLastRec
    End Get
End Property
Public ReadOnly Property BaudRate() As Integer
    Get
        Return BaudRates
    End Get
End Property
Public ReadOnly Property DataBits() As Integer
    Get
        Return DataBit
    End Get
End Property
Public ReadOnly Property StopBits() As IO.Ports.StopBits
    Get
        Return StopBit
    End Get
End Property
Public ReadOnly Property ParityBits() As IO.Ports.Parity
    Get
        Return ParityBit
    End Get
End Property

Points of Interest

The interest could arise when you do lots more with the device which you are connected with. It really helps you to understand how the communication works. I found it useful and hope it is useful to you as well. This will really help you to kick start serial port communication.

Please do send me any feedback about the code.

License

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


Written By
Software Developer (Junior)
India India
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions

 
GeneralMy vote of 1 Pin
mihi6426-Jul-10 0:08
mihi6426-Jul-10 0:08 
GeneralMy vote of 1 Pin
ivanmen3-Jul-09 5:46
ivanmen3-Jul-09 5:46 
GeneralMy vote of 1 Pin
Colin Maclean2-Jun-09 1:03
Colin Maclean2-Jun-09 1:03 
GeneralMy vote of 1 Pin
Syed J Hashmi13-Dec-08 17:58
Syed J Hashmi13-Dec-08 17:58 
Poor article
GeneralWrong Code Pin
August8music21-Apr-08 9:37
August8music21-Apr-08 9:37 
GeneralRe: Wrong Code Pin
Imran A Momin21-Apr-08 19:08
Imran A Momin21-Apr-08 19:08 
GeneralRe: Wrong Code Pin
Archdin23-Jun-08 17:51
Archdin23-Jun-08 17:51 
GeneralRe: Wrong Code Pin
clefranc28-May-09 6:15
clefranc28-May-09 6:15 

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.