Serial Port Interfacing with VB.net 2010

November 21, 2010

Articles

The serial port on our computers are with us for quite sometime now. It is more favored than the parallel port for interfacing with the outside world because it require lesser wires and can go farther distance and can even be used with newer technologies such as Bluetooth using its serial port capability. In this tutorial is a quick start guide in communicating with the serial port using VB.net without any previous knowledge.

Before we start, VB.net 2010 must be installed. The installer can be freely downloaded from Microsoft.

Start Visual Basic 2010 Express and you will be prompted with the Start Page Window

VB.net Start Page

Select on New Project and select Windows Form Application and give the Project a name, in this case I named it Serial Port Interface.

NewProject

A blank form will be displayed named Form1. This is the main form which will contain all other controls.

BlankForm

Click on the toolbox to show the  controls, you may want to click on the pin to disable the autohide feature.

Controls

Click on the form and change its name to frmMain (for easier identification specially when adding more forms). Also, change its name, in this case VB.net Terminal – Philrobotics. This name will be the one that will be displayed on the title bar.  Since this program is only a small program, we can disable the Maximize button by setting MaximizeBox value on the form’s property to false.

Let’s start to add some controls to our form. From the common Controls, add (2) two labels, (2) two combo box and (2) two buttons. Change the text of the first label to “Com Port:” and the second one to “Baud Rate:”. For the combo box change its name to cmbPort and cmbBaud for the purposes of easier identification when we will add the codes to our controls. Also, change the text of the two buttons, the first to “Connect” and the second to “Disconnect” and change their name to btnConnect and btnDisconnect. As you can see, I use cmb and btn prefix to refer to combo box and button same reason as above, for easier identification.

firsHalf

Next, from the Containers add two Group box and change its text to “Transmit Data” and “Received Data”. Inside the Transmit Data group box, add a textbox and a button. Change the name of the textbox to txtTransmit and the button to btnSend, also change its text to Send. On the Received Data group box, add a Rich Text Box and change its name to rtbReceived. Lastly and the most important, add the SerialPort from the components.

Second Half

Now, we come to the next part, adding the instructions to our program. To start coding double click the form or press F7 to view the code. To add a code to individual controls just go back to the designer view or press Shift+F7 and double click a control to add code into it.

BlankCode

For instance if we double click on the Send button on the designer view the Code Editor will take us to

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click

On this Part is where we enter our codes.

End Sub

CodeEditor

To complete our program put the following codes to the code editor:

‘Serial Port Interfacing with VB.net 2010 Express Edition
‘Copyright (C) 2010  Richard Myrick T. Arellaga

‘This program is free software: you can redistribute it and/or modify
‘it under the terms of the GNU General Public License as published by
‘the Free Software Foundation, either version 3 of the License, or
‘(at your option) any later version.

‘This program is distributed in the hope that it will be useful,
‘but WITHOUT ANY WARRANTY; without even the implied warranty of
‘MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
‘GNU General Public License for more details.

‘ You should have received a copy of the GNU General Public License
‘ along with this program.  If not, see <http://www.gnu.org/licenses/>.

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
Public Class frmMain
Dim myPort As Array  ‘COM Ports detected on the system will be stored here
Delegate Sub SetTextCallback(ByVal [text] As String) ‘Added to prevent threading errors during receiveing of data

Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
‘When our form loads, auto detect all serial ports in the system and populate the cmbPort Combo box.
myPort = IO.Ports.SerialPort.GetPortNames() ‘Get all com ports available
cmbBaud.Items.Add(9600)     ‘Populate the cmbBaud Combo box to common baud rates used
cmbBaud.Items.Add(19200)
cmbBaud.Items.Add(38400)
cmbBaud.Items.Add(57600)
cmbBaud.Items.Add(115200)

For i = 0 To UBound(myPort)
cmbPort.Items.Add(myPort(i))
Next
cmbPort.Text = cmbPort.Items.Item(0)    ‘Set cmbPort text to the first COM port detected
cmbBaud.Text = cmbBaud.Items.Item(0)    ‘Set cmbBaud text to the first Baud rate on the list

btnDisconnect.Enabled = False           ‘Initially Disconnect Button is Disabled

End Sub

Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text         ‘Set SerialPort1 to the selected COM port at startup
SerialPort1.BaudRate = cmbBaud.Text         ‘Set Baud rate to the selected value on

‘Other Serial Port Property
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8            ‘Open our serial port
SerialPort1.Open()

btnConnect.Enabled = False          ‘Disable Connect button
btnDisconnect.Enabled = True        ‘and Enable Disconnect button

End Sub

Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close()             ‘Close our Serial Port

btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub

Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text & vbCr) ‘The text contained in the txtText will be sent to the serial port as ascii
‘plus the carriage return (Enter Key) the carriage return can be ommitted if the other end does not need it
End Sub

Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())    ‘Automatically called every time a data is received at the serialPort
End Sub
Private Sub ReceivedText(ByVal [text] As String)
‘compares the ID of the creating Thread to the ID of the calling Thread
If Me.rtbReceived.InvokeRequired Then
Dim x As New SetTextCallback(AddressOf ReceivedText)
Me.Invoke(x, New Object() {(text)})
Else
Me.rtbReceived.Text &= [text]
End If
End Sub

Private Sub cmbPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbPort.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.PortName = cmbPort.Text         ‘pop a message box to user if he is changing ports
Else                                                                               ‘without disconnecting first.
MsgBox(“Valid only if port is Closed”, vbCritical)
End If
End Sub

Private Sub cmbBaud_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaud.SelectedIndexChanged
If SerialPort1.IsOpen = False Then
SerialPort1.BaudRate = cmbBaud.Text         ‘pop a message box to user if he is changing baud rate
Else                                                                                ‘without disconnecting first.
MsgBox(“Valid only if port is Closed”, vbCritical)
End If
End Sub
End Class

After putting all the codes we are now ready to compile our project. To do this go to, Debug -> Build SerialPortInterface.  If there are no errors, It will indicate Build Succeeded at the status bar.

Build

The executable file of the compiled project is usually located at the bin\Release of the project folder.

To test if our program is working, short the TX and RX pin of your serial port and  press F5 or click on the green triangle. Each data that we send must also be received by our program. In my setup I’m using a USB-to-Serial Converter and is allocated at COM18.

YouTube Preview Image

Download link for project source

, , , ,

15 Responses to “Serial Port Interfacing with VB.net 2010”

  1. glutnix_neo Says:

    Very nice article sir…

  2. tiktak Says:

    salamat po sir

  3. 7 Says:

    four thumbs up! :)

  4. Chris Pasman Says:

    Very helpful article sir.
    To those who find this article helpful dont hesitate to add your comment for future enhancement.

  5. iking Says:

    very nice!! :)
    thanks for sharing tiktak.

  6. gigz09 Says:

    very nice sir..

    will upload my C# version soon once I completely debugged it =)

    more power!=)

  7. yelong apoy Says:

    +7!!!nice sir tiktak!!!

  8. windows 8 16 bit support Says:

    prodigious article keep it up.

  9. yosa Says:

    nice! made in the philippines…

  10. arun patole Says:

    Dear Sir,
    I have written your code in VB software and built.
    In debugging, when I press Send button ,data in transmit text field
    do not display in receive window. I have shorted Tx and Rx pin of DB9
    connector. Can you provide solution over this.

  11. roshperea Says:

    nice sir..it was a big help..

  12. roshan Says:

    sir, what to do if the system is hanging while the port is connected on the computer?this is the biggest problem i can not solve..pls help..tnx

  13. roshan Says:

    sir please..i need your response on my email as soon as possible. because its about time for me to present my project tomorrow..ill wait.tnx

  14. zodzeus Says:

    Can you please sent me that link again, it was block. I have a problem when i receive data from com port, Sytem almost stop working when my app receive data

    thanks

Trackbacks/Pingbacks

  1. PhilRobotics Serial Terminal using C#.NET | PhilRobotics - January 14, 2011

    […] This is a yet another alternative application for Windows HyperTerminal and a C#.NET Version of Serial Port Interfacing with VB.net 2010. […]

Leave a Reply