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.
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.
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.
Dim NewAsyncSerialPort As New AsyncSerialPort("COM1")
Dim NewAsyncSerialPort As New AsyncSerialPort("COM1", 9600, _
IO.Ports.Parity.None, 8, IO.Ports.StopBits.One)
The other parameters are
Sending Data to the Serial Port
To send the data, you need to call the
subto do so. Let's take a look at the
Private Sub SendByte(ByVal byts() As Byte)
If Port.IsOpen = False Then
Port.Write(byts, 0, byts.Length)
You need to pass an array of
bytes, array of
stringto 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:
Private WithEvents Port As IO.Ports.SerialPort
Now, we will create a
subwhich will handle the event when the data is received:
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)
LastOffset = BufferSize
LastOffset = 0
BufferSize = 0
subwill handle the event whenever a port receives any data.
Couple of Properties within the Class
Public ReadOnly Property CurrentBufferSize() As Integer
Public ReadOnly Property TotalBytesReceived() As Integer
Public ReadOnly Property BaudRate() As Integer
Public ReadOnly Property DataBits() As Integer
Public ReadOnly Property StopBits() As IO.Ports.StopBits
Public ReadOnly Property ParityBits() As IO.Ports.Parity
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.