Posts Tagged ‘Serial Port Interfacing’

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

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

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

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

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.

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.

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.

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

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/&gt;.

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.

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.

[Updated] Downlink link for project source