Dear Readers: Welcome to The Engineering Projects


Saturday, 20 October 2012

Microsoft Visual Basic 2010 - Com Port Tutorial

Page Views:

Update: Few bugs were reported by some readers, which I have corrected and updated the code. Now, its fully tested and 100% working. I have also added comments for better understanding.

Hello friends, hope you all are enjoying the start of winter season. By the way, I really hate winter season and I just want to hibernate in this season ..... :))

Well coming to our today's lecture, my today tutorial is actually based on a request made by one of the member on my Facebook Page and as it is a really good topic so i thought to share it.

Today we will make a software on Microsoft Visual Basic 2010 in which we will send data through the COM Port i.e. serial communication. In this software we will send the data and also receive it.Simply follow all the given steps carefully, its a fully working project with code so don't do any mistake. Moreover check these two complete tutorials on Microsoft Visual Studio 2010 as well, these are quite fascinating.
First of all download the Microsoft Visual Basic 2010. The installer can be freely downloaded from Microsoft.After installing the software follow these simple steps.

Steps To Follow

Step 1 : Creating a New Project


  • Open your installed Microsoft Visual Studio 2010 software. The first interface will be something like that :
  •  Now click on the New Project and select Windows Form Applications.
  • In the project name box, add name of your project as I have added Serial Port Interface.
  • Click OK and a new window will be opened as shown in below image which contains a blank Form1.
  • In this Form1 we are gonna add our controls buttons etc.

Step 2 : Changing Name of Form


  • Now click on the form1 and the properties panel will be open on the right side. Now, in the properties tab shown on the right side change its name to frmMain (for easier identification specially when adding more forms).
  • Also change the text of the form to something you like as Serial Terminal. This will be shown on the title bar of your application.
Step 3 : Adding Controls To The Project


  • Lets start to add some controls in our software like buttons,combo box and labels etc.
  • So from the Common Controls tab add two buttons, two combo boxes and two labels into your Form1 and  align them as shown below :
  • For Button 1, change the text to Connect and change the name to btnConnect.
  • For Button 2, change the text to Disconnect and change the name to btnDisconnect.
  • For Combo Box 1, change the name to cmbPort.
  • For Combo Box 2, change the name to cmbBaud.
  • For Label 1, change the text to Comm Port.
  • For Label 2, change the text to Baud Rate
Note :
  • Keep the names and texts of same character as i wrote them.
  • They are case sensitive so be careful. I will recommend to just copy paste them.
  • If you make even a one letter mistake the code will not run.
  • btn and cmb are just to remind that they are button and combo box respectively. Its better to do neat programming.
Step 4 : Adding Serial Port & Boxes


  •  Now from Container tab, add two Group Boxes in the forum.
  • Change the name of Group Box 1 to Transmit Data.
  • Change the name of Group Box 2 to Received Data.
  • Now add a Text Box and a Button in the Transmit Data Group Box.
  • Change the name of the Button to Send and text to btnSend.
  • Change the name of the Text Box to txtTransmit.
  • Now add a Rich Text Box in the Received Data Box and change its text to rtbReceived.
  • Arrange all these components as shown in the below image :
  •  Lastly and i think its the most important part of this tutorial, add a Serial Port Block into your forum. It will appear at the bottom. Don't change any of its parameters just leave it as it is.
Step 5 : Coding Section


  • Now we come to the coding part of our project. If you double click on your forum, it will open a new window something like that :
  • This is the place where we add our code and in other words add functionality to our project, this window is called Code Editor.
  • If you double click on any button or box, its respective code will created in this region automatically.
  • Now what you need to do is copy the below code and paste it in your code editor window. 
  • Just remove all the previous code in your Code Editor Window.
  • Here's the code :
'Code Starts here ....
'Import Systems which we are gonna use in our code
Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports


'frmMain is the name of our form ....
'Here starts our main form code .....
Public Class frmMain
Dim myPort As Array
Delegate Sub SetTextCallback(ByVal [text] As String)


'Page Load Code Starts Here....
Private Sub frmMain_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
myPort = IO.Ports.SerialPort.GetPortNames()
cmbBaud.Items.Add(9600)
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)
cmbBaud.Text = cmbBaud.Items.Item(0)
btnDisconnect.Enabled = False
End Sub
'Page Load Code Ends Here ....


'Connect Button Code Starts Here ....
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
SerialPort1.PortName = cmbPort.Text
SerialPort1.BaudRate = cmbBaud.Text
SerialPort1.Parity = IO.Ports.Parity.None
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.DataBits = 8
SerialPort1.Open()
btnConnect.Enabled = False
btnDisconnect.Enabled = True
End Sub
'Connect Button Code Ends Here ....


'Disconnect Button Code Starts Here ....
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
SerialPort1.Close()
btnConnect.Enabled = True
btnDisconnect.Enabled = False
End Sub
'Disconnect Button Code Ends Here ....


'Send Button Code Starts Here ....
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSend.Click
SerialPort1.Write(txtTransmit.Text)
End Sub
'Send Button Code Ends Here ....


'Serial Port Receiving Code Starts Here ....
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
ReceivedText(SerialPort1.ReadExisting())
End Sub
'Serial Port Receiving Code Ends Here ....


'Serial Port Receiving Code(Invoke) Starts Here ....
Private Sub ReceivedText(ByVal [text] As String)
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
'Serial Port Receiving Code(Invoke) Ends Here ....


'Com Port Change Warning Code Starts Here ....
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
Else
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
'Com Port Change Warning Code Ends Here ....


'Baud Rate Change Warning Code Starts Here ....
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
Else
MsgBox("Valid only if port is Closed", vbCritical)
End If
End Sub
'Baud Rate Change Warning Code Ends Here ....


End Class
'Whole Code Ends Here ....
  • After adding the code your Code Editor Window will look something like this one :

Step 6 : Compile Your Project


  • After adding all the code, now you are ready to compile your code and run your application.
  • To compile go to Debug -> Build SerialPortInterface and if everything's going right then your project will pop up.
  •  To test your application, just add some LCD to your serial port or simply short your Rx Tx pins and whatever you send you will receive it.
  • Here's the image of my final application. I have converted it to .exe file, in my coming tutorials i will tell you how to convert a project to .exe file.
Note :
  • The project exe file and the complete code has already been emailed to all our subscribed members.
  • If someone didn't get it or want to get these files then first Subscribe to Our Newsletter and then post your email here and I will email it to them.

If you don't want to get yourself into Serious Technical Trouble while doing your programming OR technical projects then just sit back and relax and let us do the Job for you at a fairly reasonable cost. Submit your project details by Clicking Here »

About the Author

I am Syed Zain Nasir, the founder of The Engineering Projects (TEP). I am a programmer since 2009 before that I just search things, make small projects and now I am sharing my knowledge through this platform.I also work as a freelancer and did many projects related to programming and electrical circuitry.

In 61 people's circles

Subscribe To Get FREE Tutorials!

35 comments:

  1. another great tutorial i will surley try this one as high level programming is my passion

    ReplyDelete
  2. i couldnt understand this Invoke part what is its functionality

    ReplyDelete
  3. saim_lodhi89@hotmail.com
    this is my id please send the code to my email id
    i have subscribed to the newsletter really need this one
    thanks in advance

    ReplyDelete
  4. @kashif Thanks bro for appreciation and yups try it and let me know howz you find it.

    @Seol This Invoke function is used actually to automatically called every time a data is received at the Serial Port. Its kind of an interrupt for the coming data.

    @saim lodhi The code and the software has been sent bro, check your email id. and stay connected ... :))

    ReplyDelete
  5. thnx bro file received

    ReplyDelete
  6. Kindly mail me the code and software. I have subscribed to your mailing list.
    this is my mailing list gopsi1234@gmail.com

    ReplyDelete
    Replies
    1. A mail with the title "Serial Terminal" has been sent to you .... If you still have any problem please ask in comments and let us resolve your issues .... Thanks.

      Delete
  7. Hello,

    I have problem with this. SerialPort1 is not declared

    ReplyDelete
    Replies
    1. Check the last line of Step4 ..... " Lastly and i think its the most important part of this tutorial, add a Serial Port Block into your forum. It will appear at the bottom. Don't change any of its parameters just leave it as it is."

      I think you didn't add the serial port block in your project that's what causing problem and if you have added then make sure the name of your serial port block is SerialPort1 .... you can change it in the properties.

      Delete
  8. Awesome tutorial. Much appreciated.

    ReplyDelete
    Replies
    1. Thanks for appreciation bro .... :))

      Delete
  9. Thank you very much! I will use you code for base to create a new one.
    Good work!
    Grettings

    ReplyDelete
    Replies
    1. Thanks for the appreciation bro .... :))
      Cheers !!!

      Delete
  10. Hi,
    my name is Laurentiu and just joined the site today. I am also interested to obtain the above code. Could you please sent it to me at: vj_lau@yahoo.com

    Many thanks in advance !!!

    ReplyDelete
    Replies
    1. I have sent the email on the provided email ID .... Kindly follow the instructions in the mail.

      Thanks.

      Delete
  11. This comment has been removed by the author.

    ReplyDelete
  12. I'm have a problem: When I start your program there are no ports in the pulldown. I have tried using the 'myPort = IO.Ports.SerialPort.GetPortNames()' before without getting any ports.
    Could this be computer related?

    ReplyDelete
    Replies
    1. Before running the project .... make sure that you have connected the COM Port with your computer .... As it automatically detects all the ports so if there's no port already available then it creates problem.

      Moreover, have you changed the name of Form1 to frmMain ? Double check it.

      If still having problem, let me know.

      Delete
    2. No change. Will it detect virtual serial ports via usb when there is no actual serial port on the computer?

      Delete
    3. Yeah it will detect that usb port .... I think you are using serial to usb converter .... make sure that you have installed the drivers correctly and some COM has been assigned to your cable like COM3 etc ....

      The best way to test the software is via virtual port .... the port you are taking is not virtual .... virtual is actually a software port which doesn't exist but operates virtually (software level) ...

      Delete
  13. hello i am jashwanth My email ID is jashwanthreddy09@gmail.com
    Can you please send me the code . I need it urgently.

    ReplyDelete
    Replies
    1. Hi bro, We couldn't find your your email in our subscriber list .... Kindly subscribe to us and the files will emailed to you .... Thanks.

      Delete
  14. Hi. Can i ask something. I already follow all your instructions. I can debug the code. But when i click on Connect button, error message popup stated that "UnauthorizedAccessException was unhandled. Access to the port 'COM4' is denied. It is because i used virtual serial port? I used proteus, eltima virtual serial port and microc pro for PIC.

    ReplyDelete
    Replies
    1. Hello, the problem is Proteus doesn't support virtual serial port .... It once happens to me as well .... try this software independently via hardware ....

      Thanks.

      Delete
    2. Now i have another problem. It stated that i have no permission or the file is read only. My email kay.own90@gmail.com

      Delete
    3. Your id is not appearing in our subscription list .... Subscribe to our newsletter and the complete project will be forward to you ....

      Thanks.

      Delete
  15. Hello nasir,
    i am vishnu,i have subscribed would please send me the code my mail id:-vishnu471@gmail.com.
    Thanks

    ReplyDelete
    Replies
    1. Hi bro,

      Thanks for subscribing to our newsletter. I have emailed you the complete project.

      Thanks.

      Delete
  16. Hi bro,
    i am using visual studio 2010 c++,i have try to made terminal using c++ windows form applications.i tried run exe file on other pc which don't have studio it showing errors.i changed the settings project->properties-> cofiguration->c++->codegeneration->multi threaded(mt). after changing settings also i'm getting errors.what is the solution for this? give reply asap.
    thanks

    ReplyDelete
    Replies
    1. Actually such applications need .NET Framework so make sure that the other computer has it ...

      Delete
  17. Hi Nasir,

    I have got this problem as below,
    The PortName cannot be empty.
    Parameter name: PortName
    The list of com port does not drop down as well. It is blank when I run the program. I really appreciate your help.

    Regards,
    Teh

    ReplyDelete
    Replies
    1. Hi,

      Actually you are getting the problem because you haven't attached any COM Port with the computer on which you are running it .....

      So, before running this software first attach some COM Port or create a virtual COM Port.

      Thanks.

      Delete
  18. Hi,
    My name is Nimal Rathnaweera and just joined the site today. I am also interested to obtain the above code. Could you please sent it to me at: nratnaweera@gmail.com

    Many thanks in advance !!!

    Nimal

    ReplyDelete
    Replies
    1. Code has been sent to given email id .... If you couldn't find it then check your trash folder.

      Thanks.

      Delete

 

Recent Posts

Join Me On Facebook

3000+ Followers

Followers

Recent Comments

Follow Me On Twitter

1112+ Followers