Serial Port Programming using Visual Basic.Net for Beginners

Pinterest icon

serial port programming using Visual basic and dot net framework tutorial

Hello folks,

Visual Basic.net is an easy to learn language from Microsoft for the windows platform.One of the cool features of Visual Basic.net is the ability to whip up good looking gui components with a few lines of code.

In this tutorial we are going to use Visual Basic.net to program your PC's Serial Port and communicate with an embedded microcontroller like MSP430 or 8051.

In the first section of our tutorial we will build a simple command line program that would show us how to read and write from the Serial port using Visual Basic.net.Here we are going to use the SerialPort Class provided by the dot net framework to access the port using vb.net code.

The code may look similar to Serial Programming using C# tutorial since we are using the same dotnet framework 

Sourcecodes

link to xanthium enterprises repo on Github containing code for serial communication between PC and Micro Controller using Visual basic.net  

All the VB.net (.vb) source files used in this tutorial can be downloaded from our GitHub Page.

If you are new to Github Check this article to download code .

Creating a Vb.net Project 

For compiling and running the code we are using Visual Studio IDE from Microsoft.You can also use the opensource Sharpdevelop IDE for running the command line programs.One problem with the latest version of Sharpdevelop IDE (5.1) is the lack of Visual GUI builder for Visual Basic.net projects.

Now double click on the Visual Studio Icon and Create a new Console Project  for Visual Basic as shown below 

creating a visual basic project for programming the serial port on windows using dot net framework

If you select the " Empty Project " option instead of the " Console Application " ,the Command line window will not be visible while debugging your Project,

So stick with the " Console Application " option.

After you have pressed the OK button, the IDE will create a file named Module1.vb under the Project folder as shown below

creating a visual basic .net project using MS visual Studio

You can rename the Module1.vb to any name of your choice (here SerialCommWrite)  by right clicking on the file in the Solution Explorer and selecting Rename

Renaming a Visual basic file in Visual Studio

A dialog will popup asking you to confirm the action.Press OK 

Now your file name under your Solution Explorer as well as the Module name on the Source file will be changed to the one specified by you (here SerialCommWrite)

Now you can add your code for controlling the serialport under Sub Main() and start Programming. 

Adding Files to Your Project  and Compiling

Instead of typing your own code under the Sub Main() you want to add the downloaded source files from github directly under your Project Tree .You can first delete the IDE created Module1.vb file from the source tree by right clicking on it and choosing the "Delete" option.

Please note that choosing the "Delete" option would permanently delete your source file from the harddisk,if you just want to exclude the file from compilation just choose "Exclude From Project" option.

Then right click on your Project name and select " Add " Existing Item.."  and browse towards the files you want to add.

After adding the files to your Project you can compile them by pressing F5 or by clicking on the Start Button.

debugging your visual basic serial communication program using MS Visual Studio

Compile Time Errors

After compiling the program, if you are getting an Error Message similar to this on the Error Window

Error    1    'Sub Main' was not found in 'Serial_Comm_CMDline.Module1'.    Serial-Comm-CMDline

Sub Main was not found error visual basic dot net

Right Click on your Project Name (here Serial-Comm-CMDline) on Solution Explorer and Choose Properties 

solving-Sub-Main-was-not-found-error-vb-net

Now in the Properties Window,Under " Application "   " Startup object " ,Select the name corresponding to your Module name .

In this case, Select SerialCommWrite instead of Module1 and then compile your application. 

Accessing SerialPort Class using VB.net 

Here we are going to access the SerialPort Class from the dot net framework using Visual Basic.net to communicate with the Hardware Serial Port.In case your PC /Laptop do not have any hardware serial ports as newer models tend to do,you can use a USB to Serial Converter like USB2SERIAL for communicating with the external  device.

Before you can use the SerialPort class you have to import the dot net namespace corresponding to it .This can be done by using the Imports Keyword as shown below. 

Imports System          'To Access Console.WriteLine()
Imports System.IO.Ports 'To Access the SerialPort Object

You can find out  Serial ports (COM ports ) both real and virtual ,attached to your PC by going to the Device Manager .

You can also find out the serial ports attached to your PC programmatically using the SerialPort.GetPortNames() method .

The GetPortNames() method returns an array containing all the COM ports attached to your computer.The COM port names returned by GetPortNames() method is stored in the AvailablePorts array. A  For Each loop is then used to print the available ports on the command line .

You can display the ports connected to your computer by using the following snippet of code .

Dim AvailablePorts() As String = SerialPort.GetPortNames()

Console.WriteLine("Available Ports ::")

Dim Port As String

For Each Port In AvailablePorts
        Console.WriteLine(Port)
Next Port

Configuring the SerialPort 

We define MyCOMport as an object of type SerialPort class and then instantiate it using the new keyword.

After the object is created we then provide the name of the SerialPort,Baudrate at which to communicate ,Number of Stop/Start bits etc . 

Dim MyCOMPort As SerialPort   
MyCOMPort = New SerialPort()

MyCOMPort.PortName = "COM82"   'Assign the port name to the MyCOMPort object
MyCOMPort.BaudRate = 9600      'Assign the Baudrate to the MyCOMPort object
MyCOMPort.Parity   = Parity.None   'Parity bits = none  
MyCOMPort.DataBits = 8             'No of Data bits = 8
MyCOMPort.StopBits = StopBits.One  'No of Stop bits = 1

Reading and Writing into SerialPort

Before reading and writing into the serial port we should open a connection using MyCOMPort.Open() method.

After you have successfully opened the connection you can write into the port using MyCOMPort.Write() Method or Read from the port using MyCOMPort.ReadLine()  .

After you have completed your transaction you should close the port using  MyCOMPort.Close() method.

Writing into Serial Port

Here is a short snippet of code for writing into serial port.Here we are sending an ASCII "A" to the Serial Port.

The full Source file " SerialCommWrite.vb " can be downloaded from our Github Page .

MyCOMPort.Open()               ' Open the port
MyCOMPort.Write("A")           ' Write an ascii "A"
MyCOMPort.Close()              ' Close port

Here is a screenshot of  SerialCommWrite.vb "  running on Windows7

writing into Serial Port using Visual Basic .net

Reading from Serial Port

Here is a short snippet of code for Reading from SerialPort .Here we define a string variable called DataReceived for storing the data send from the microcontroller to the PC . MyCOMPort.ReadLine() waits till data is received and returns when a new line character ("\n") is encountered.The received data is then stored in DataReceived .

Please remember to add a new line character to the text string transmitted by  embedded system side. 

The full Source file " SerialCommRead.vb " can be downloaded from our Github Page .

Dim DataReceived As String          'To Store the Received Data

MyCOMPort.Open()                    ' Open the port
DataReceived = MyCOMPort.ReadLine() ' Waiting for Data to be send 
MyCOMPort.Close()                   ' Close port

Here is a screenshot of  SerialCommRead.vb "  running on Windows7

waiting for Data to be received

Data received by the PC 

reading a serial port using vb.net

Hardware Connections 

If your PC does not have any hardware serial ports you can use any USB to Serial Converters(I am using USB2SERIAL).

I have interfaced a microcontroller board(MSP430G2553 on Launch Pad) to the serial port using a null modem cable like this

Null modem serial connection between microcontroller(MSP430) and PC serial port using USB2SERIAL and visual basic .net

You can use any microcontroller of your choice like 8051,AVR or ARM(LPC2148).The Controller waits for a character to be received and lights up the corresponding LED. The code for MSP430 is included in the zip file.If you want to know how to configure the MSP430 controller UART you can check this tutorial.

interfacing MSP430 Launchpad with PC using VisualBasic .net and USB to RS485/serial Converter
Please note that if you are using a DB9 RS232 Serial Port of your PC, you will have to build a RS232 signal level converter at the microcontroller side to decode the RS232 signal.
Directly connecting the PC's RS232 Serial port to MSP430 's pins will damage the chip.

 

Comments

Nice article

add a gui building tutorial also