Serial Port Interfacing with VB.net 2010

Posted: November 21, 2010 in Tutorials
Tags: , , , , , ,

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

Comments
  1. David says:

    Good JOB!!
    From Peru

  2. thoughtdraw says:

    Thankyou so much, I have been struggling to understand the finer detail of invoke and delegates properly. This tutorial has helped immensely! I can now start start building my programme with this clear in my head!

  3. Davis says:

    This is phenomenal! I’m working on building a PICAXE-based ROV (my first experience with a microcontroller) and I haven’t used VB very much at all. This is one of the few complete sets of instructions out there for VB.net 2010, and it’s exactly what I need to help me out. Thanks much!

  4. Dan D. says:

    Totally new to Visual Basic. Many thanks! This appears to have saved me weeks of learning and frustration. On to the next portion of my application.

  5. Peter Keller says:

    Great help, thanks
    Pedro

  6. doki doki says:

    cmbPort.Items.Item(0)
    InvalidArgument=Value of ‘0’ is not valid for ‘index’.
    Parameter name: index

    i got this error, what does this mean?

    • tiktakx says:

      @doki doki
      do you have a com port installed? if there is none the program cannot read any serial port so that error comes out

      • jayjay says:

        these program can be helpful in my project regarding transmitting data..
        but there is no com port exist when i run my program..
        and when i checked my device manager there is no COM1,COM2.. im using sony viao laptop..

        how to solve this problem??

  7. doki doki says:

    i am using your coding to connect to a PIC16F877A via bluetooth. my laptop has a bluetooth installed and the PIC is connected to a bluetooth module. any modification that i need to do to the vb so that my laptop can connect to the PIC?

    • tiktakx says:

      I use this same code with bluetooth to control a mobile robot with 16F628a, be sure that there is a bluetooth com port installed in your PC, check your device manager

    • ever says:

      can you share with me about your coding.i am interested to know how it works.i am also use PIC16F877A and skkca-21 for my project.

  8. doki doki says:

    there is no ports tree in my device manager, is this the problem?

  9. doki doki says:

    btw, i am using windows 7 home premium

  10. doki doki says:

    my asus bios doesn’t have options to enable ports, any other options to use ports?

    • tiktakx says:

      yup that’s the problem, usually if you install a bluetooth dongle it usually install a serial port, if there is none right click on the bluetooth icon open settings go to com port and add, that should solve your problem

  11. doki doki says:

    do you have example of coding for pic to PC through a bluetooth module? I am using PICBasic Pro as my source code.

  12. doki doki says:

    INCLUDE “modedefs.bas” ‘Serial communication mode definition file
    DEFINE OSC 20
    TRISC = %00000001
    PortC = 0
    TRISB = %11111111
    TRISC = %00000000
    PortD = 0
    SPBRG = 10
    TXSTA=$24 ‘ enable transmit and SPBRGH=1
    RCSTA=$90 ‘ Enable USART and continuous receive
    B1 Var byte
    B1 = “2”
    mainloop:

    IF (PortB.7 = 1) THEN
    TXREG = B1
    HIGH PortD.2
    PAUSE 2000
    LOW PortD.2

    ENDIF

    GOTO mainloop
    END

    i can’t receive any data from the PIC using this coding, any suggestions?
    it works well for uart connections.

  13. doki doki says:

    the coding can’t work with Bluetooth module (SKKCA-21)

  14. tiktakx says:

    I havent used that BT module before, but test your system first with hyperterminal, It’s just like a normal UART when working with BT except when the BT module needs extra initialization routine

  15. Gerber says:

    Hi

    I using the IO.Ports.SerialPort.GetPortNames to get the avaible comport names. This works fine with the cabled comport but the bluetooth comport sometimes give extra characters at the end of the comport name. Below are some examples

    COM3 is shown as COM3 or COM3i or COM31
    COM9 is shown as COM9 or COM9c or COM92
    COM31 is shown as COM31 or COM31i

    I am able to coupe with removing the end character if it is not a number (e.g. COM3i converted to COM3) but how do I remove the extra characters if they are numerical (e.g. COM31 converting to COM3) please note that sometimes the comports are displayed correctly.

    Is there a way to of solving this and retreiving the correct comport names without the extra digits.

    Thank you for any help in advance.

    • tiktakx says:

      I dont know about the comport why it has a non numeric character after, but if it is detected as COM32 then it should work no need to convert to com3, please verify on your device manager or try to re install you bluetooth dongle, working fine with mine using a cheap bluetooth usb dongle. This was my application before on bluetooth control http://www.youtube.com/watch?v=VKPx3Orld1k

  16. doki doki says:

    tiktakx :
    I havent used that BT module before, but test your system first with hyperterminal, It’s just like a normal UART when working with BT except when the BT module needs extra initialization routine

    can you give me examples of extra initialization routine? I have trouble finding examples…

  17. tiktakx says:

    It depends on your bluetooth module, consult the datasheet, is it working already with hyperterminal? is the baudrate correct? because in my code I make it default to 9600 based on this site http://cytron.com.my/userpage.php?id=PR6A the default baud rate is 115200 so try to change this in your code

  18. doki doki says:

    sorry to disturb again, but why is this coding displaying ?? in the rtbReceived.Text.
    i used a uart to establish connection with a pc
    INCLUDE “modedefs.bas” ‘ Serial communication mode definition file
    DEFINE OSC 20 ‘ Oscillator speed is set to 20MHz
    TRISB = %11111111
    TRISC = %10000000 ‘ RC.7 => USART RX pin set to input
    PortC = 0
    SPBRG = 25 ‘ Baud Rate = 9600

    ‘ Variable definition
    ‘ ===================

    DataOut var byte ‘ use to store TXREG content
    DataIn var byte ‘ use to store RCREG content
    DataIn = 0
    DataOut = 0

    mainloop:

    TXSTA = $24 ‘ enable transmit and SPBRGH = 1
    RCSTA = $90 ‘ Enable USART and continuous receive
    datain = DataOut ‘ Get data

    IF (PortB.7 = 1) THEN
    DataOut = DataIn + 1
    PAUSE 1000
    DataIn = DataOut
    TXREG = DataOut ‘ Transmit Data

    HIGH PortD.2
    PAUSE 2000
    LOW PortD.2

    ENDIF

    GOTO mainloop
    END

    • tiktakx says:

      I see a baudrate problem, because from the site that I posted above the default baud rate of your Bluetooth is 115200bps maybe change it first to 9600 then check it again

  19. doki doki says:

    now i am using usb to uart for connection http://www.cytron.com.my/viewProduct.php?pid=JB4nHTECFzU2KwsnABsbNvDwRDzznQ7nn82zcVu7Ut0=
    any idea why random characters are shown at the rich text box?
    i already change the code – baud rate:

    INCLUDE “modedefs.bas” ‘ Serial communication mode definition file
    DEFINE OSC 20 ‘ Oscillator speed is set to 20MHz
    TRISB = %11111111
    TRISC = %10000000 ‘ RC.7 => USART RX pin set to input
    PortC = 0
    SPBRG = 129 ‘ Baud Rate = 9600

    ‘ Variable definition
    ‘ ===================

    count01 VAR BYTE ‘ variable to store TXREG content
    TXSTA = %00100100 ‘ Enable transmit and asynchronous mode
    RCSTA = %10010000 ‘ Enable serial port and continuous receive
    mainloop:

    IF (PortB.7 = 1) THEN
    FOR count01 = 1 TO 30

    PAUSE 2000

    TXREG = count01 ‘ Transmit Data

    HIGH PortD.2
    PAUSE 2000
    LOW PortD.2

    Next

    ENDIF

    GOTO mainloop

    END

  20. tiktakx says:

    can you try this, load this hex to a PIC16F877a with 20Mhz crystal, set baudrate of VB.net to 9600, connect TX of PIC to RX of PC and RX of PIC to TX of PC. just paste it in notepad and save it as whatever.hex then burn it with your programmer

    :1000000000308A0075280000C8326C366F10D73770
    :1000100072366410F437202B4217EE327410E23C33
    :10002000202AE935F430EB060A00831603178C17F3
    :100030000C140000000083120C087F3903195B28A0
    :100040000313A10003170D080313A20003170F08E1
    :100050000313A30021080C1E2B2899002208031764
    :100060008D000313230803178F0083168C170C14BD
    :100070000000000083120C0D0E0D7F3903195B2860
    :100080000313A10003170D080313A20003170F08A1
    :100090000313A30021080C1E4B2899002208031704
    :1000A0008D000313230803178F008D0A03198F0A8D
    :1000B00003131528031703138A110A1290282230FC
    :1000C000840083130008031972280630F800F70132
    :1000D000F70B6828F80B67287B30F700F70B6E28C2
    :1000E000800B65288A110A129528840183131F301A
    :1000F0008305813083169900A630980090308312D2
    :10010000980083161F149F141F159F1107309C0021
    :100110000430831203178D0000308F00031315285D
    :100120000430A100FA30A2005F28A10B92288316A8
    :0401300088286300B8
    :02400E007A1F17
    :00000001FF

  21. doki doki says:

    nvm, i got the program right..

    INCLUDE “modedefs.bas” ‘ Serial communication mode definition file
    DEFINE OSC 20 ‘ Oscillator speed is set to 20MHz
    TRISB = %11111111
    TRISC = %10000000 ‘ RC.7 => USART RX pin set to input
    PortC = 0
    SPBRG = 129 ‘ Baud Rate = 9600

    ‘ Variable definition
    ‘ ===================

    count01 VAR BYTE ‘ variable to store TXREG content
    TXSTA = %00100100 ‘ Enable transmit and asynchronous mode
    RCSTA = %10010000 ‘ Enable serial port and continuous receive
    mainloop:

    IF (PortB.7 = 1) THEN
    FOR count01 = 1 TO 30

    PAUSE 2000

    TXREG = count01 + $30 ‘ Transmit Data

    HIGH PortD.2
    PAUSE 2000
    LOW PortD.2

    Next

    ENDIF

    GOTO mainloop

    END

  22. doki doki says:

    The result displayed in Hyperterminal:
    ASCII Character: 1, 2, 3, 4, 5, 6, 7, 8, 9, :, ; < until the 30th ASCII Character

    referred to page 203, PIC MCU With PICBasic [Chuck Hellebuyck]

    tiktakx, 1 Question: How do i convert the ASCII characters i received via serial port into integers?

  23. doki doki says:

    i meant in vb’s serial port?

  24. doki doki says:

    can i ask for your coding for PC to micro controller communication? i need some reference.
    i used the coding below:

    INCLUDE “modedefs.bas” ‘ Serial communication mode definition file
    DEFINE OSC 20 ‘ Oscillator speed is set to 20MHz
    TRISB = %11111111
    TRISC = %10000000 ‘ RC.7 => USART RX pin set to input
    PortC = 0
    SPBRG = 10 ‘ Baud Rate = 9600

    ‘ Variable definition
    ‘ ===================

    count01 VAR BYTE ‘ variable to store TXREG content
    TXSTA = %00100100 ‘ Enable transmit and asynchronous mode
    RCSTA = %10010000 ‘ Enable serial port and continuous receive
    mainloop:

    IF (PortB.7 = 1) THEN
    FOR count01 = 0 TO 9

    PAUSE 2000

    TXREG = count01 + $30 ‘ Transmit Data

    HIGH PortD.2
    PAUSE 2000
    LOW PortD.2

    Next

    ENDIF

    GOTO mainloop

    END
    For PIC {UART} to PC serial communication it works fine, only for PIC [Bluetooth]
    to PC, both Hyperterminal and VB2010, nothng is received.

  25. doki doki says:

    my baud rate is set to 115200 now.

    • tiktakx says:

      I use CCS C/HI-TECH C mostly I am not really familiar with BASIC language
      for CCS C to test if PIC to PC I usually use this code

      #include
      #FUSES HS, NOWDT, PUT, PROTECT, NOLVP
      #use delay(clock = 20M)
      #use RS23(baud = 9600, xmit = PIN_C6, rcv = PINC7)

      void main ()
      {
      while(true)
      {
      printf(“Hello\r\n”);
      delay_ms(1000);
      }
      }

  26. doki doki says:

    tiktakx, thank you for replying my messages. Now my BT works fine now.

  27. doki doki says:

    tiktakx, i will like to use arrays to store data from the serial port.

    Which part of your coding should I modify? Can you give me an example?

    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

  28. Louie says:

    tiktakx,
    Thank you so much for sharing your time and information with everyone. I searched all over for a tutorial to get me started since this is my first time ever using VB 2010. It was the last and most dreaded part of my project and now I can go to bed knowing I’m on the other side of a huge mountain, it’s all down hill from here thanks to you!

  29. WilliamCeng says:

    Tiktaxx, i want to ask about your program. i have used it on my way to build a communication. it is working until

    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.

    the error message coming :

    system.InvalidOperationException {“The port is closed.”} shown on my window. it is coming because the port is connected or there is another error? pliz explain i need this program

  30. doki doki says:

    does serial port only receives data in string?

  31. doki doki says:

    How about textbox in vb? What type of variables is that? How do i convert any characters typed to textbox into integers? CInt and Asc doesn’t work…

    Example of non-working code:

    Dim variable As Integer
    variable = Asc(txtbox1.Text)
    lbl1.Text = variable.ToString

    or

    Dim variable As Integer
    variable = CInt(txtbox1.Text)
    lbl1.Text = variable.ToString

    or

    Dim variable As Integer
    variable = CInt(Asc(txtbox1.Text))
    lbl1.Text = variable.ToString

  32. doki doki says:

    But why do this coding works?

    Input from PIC:

    count01 VAR BYTE
    count01 = %00000001
    TXREG = count01

    PC displays:

    1

    Private Sub ReceivedText(ByVal variable As String)
    ‘compares the ID of the creating Thread to the ID of the calling Thread
    Dim i As Integer = 0
    If Me.lblResult.InvokeRequired Then
    Dim x As New SetTextCallback(AddressOf ReceivedText)
    Me.Invoke(x, New Object() {(variable)})
    Else
    i = Asc(variable)
    variable = i.ToString()
    Me.lblResult.Text &= [variable]
    End If
    End Sub

  33. Manuel says:

    Nice job!
    I’ve tried your project on an OCR scanner over Com Port (with Serial-to-USB) and when wanna send a command, recive only “?” in TextBox (under recived data).
    If I’ll need some help about programming with COM port, can I write to you?

    • tiktakx says:

      hi, please check if the baud rate of the PC and the OCR is the same

      • evilmanu says:

        I’ve checked on manual and have “rate: 150 – 38400 Baud”. I’ve tried to change che baud rate and have different results, as “xx”, “f?”, “??” and “” (empty).

        ps: I have a prog. That prog read the result od OCR scanner over COM port. But I need to send command/s to decive to start read. How can I find that? I’ve tried some com port monitor but not working with results I’ve recived (HEX). I’m trying to use that HEX but don’t happen anything. What is wrong?

        Thanks in advance

        Manuel

  34. doki doki says:

    i need some advice.

    My PIC wants to send information to the PC twice. For example, one is the x-coordinate and the next is the y-coordinate.
    If i use the DataReceived event, wouldn’t the program return to _DataReceived() subroutine each time a new data is received?
    Will that mean that the serial port will be overwritten and i will never get the first data sent or x-coordinate?

  35. GideonB says:

    Great little tutorial. Clear, concise and commented code to seal the deal. Thanks for the share tiktakx

  36. Louie says:

    Hi tiktakx,
    Thanks again for the tutorial, it’s helped me get started with no formal VB background. I modified what you provided to COPY and CLEAR the data from the RTB and it works fine.
    Then added this function after many hours of head scratching:
    Private Sub rtbReceived_TextChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles rtbReceived.TextChanged
    Dim DTS As String
    DTS = (“$DATETIME,”)
    Dim RX_string As String
    RX_string = (“$REQTIME,1″)
    If SerialPort1.ReadExisting = RX_string & vbCrLf Then
    SerialPort1.Write(DTS & DateAndTime.DateString & ” ” & DateAndTime.TimeString & vbCrLf)
    End If
    End Sub

    It sends the Date/Time stamp in response to receiving the “$REQTIME,1” just fine, every time, but now it loses some received messages. For instance, my application will request to read 510 4 byte long messages and it will only display anywhere from 256 to 300+ messages. But if I comment out this function I get all 510 messages in the RTB.
    Is there a way to switch this function ON/OFF during another function or is it just written wrong?
    Thanks for your help.

  37. doki doki says:

    Delegate Sub aSetTextCallback(ByVal Rohead As String) ‘Added to prevent threading ‘errors during receiving of data

    Delegate Sub bSetTextCallback(ByVal Rodir As String) ‘Added to prevent threading ‘errors during receiving of data

    Private Sub Bluetooth_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Bluetooth.DataReceived
    ReceivedText(Bluetooth.ReadByte) ‘Automatically called every time a data ‘is received at the Serial Port
    End Sub

    Private Sub ReceivedText(ByVal variable As Integer)

    Dim Rohead As String = “??”
    Dim Rodir As String = “?!”

    If Me.lblRobHead.InvokeRequired Then
    Dim y As New aSetTextCallback(AddressOf ReceivedText)
    Me.Invoke(y, New Object() {(Rohead)})
    Else
    Me.lblRobHead.Text &= [Rohead]
    End If

    I am trying to use delegate and invoke because the DataReceived prevents me from
    updating label content

    but i always get this message during runtime

    {“Input string was not in a correct format.”}

    Any ideas?

  38. doki doki says:

    I am sorry to bother you, tiktakx but do have any method to set value of labels
    example:
    Dim va2lue As Integer = 2
    lblCoordinate.Text = va2lue.ToString
    if this statement is inside the following sub routine

    Private Sub Bluetooth_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles Bluetooth.DataReceived
    ReceivedText(Bluetooth.ReadByte) ‘Automatically called every time a data is received at the Serial Port
    End Sub
    Private Sub ReceivedText(ByVal variable As Integer)

    Dim va2lue As Integer = 2
    lblCoordinate.Text = va2lue.ToString

    I always get this message:

    {“Cross-thread operation not valid: Control ‘lblCoordinate’ accessed from a thread other than the thread it was created on.”}

    i tried your delegate method but didn’t work:

    Delegate Sub aSetTextCallback(ByVal Rohead As String) ‘Added to prevent threading ‘errors during receiving of data

    If Me.lblCoordinate.InvokeRequired Then
    Dim y As New aSetTextCallback(AddressOf ReceivedText)
    Me.Invoke(y, New Object() {(Rohead)})
    Else
    Me.lblCoordinate.Text &= [Rohead]
    End If

  39. doki doki says:

    it seems like DataReceived event has a lot of limitations.

    It is best to use non-string variables type, right? I can’t even enable the timer via timer1.enabled = true if the statement is inside the DataReceived event and

    If i use select case

    Select Case MaVa
    Case 0
    Rohead = “North”
    Case 1
    Rohead = “East”
    Case 2
    Rohead = “South”
    Case 3
    Rohead = “West”
    Case Else
    Rohead = “?!”
    End Select

    The string value stored, Rohead is not modified although the variable is declared just underneath the Public Class…

  40. doki doki says:

    I tried:

    Delegate Sub aSetTextCallback(ByVal Rohead As String) ‘Added to prevent threading errors during receiving of data

    Inside DataReceived event subroutine:

    If Me.lblRobHead.InvokeRequired Then
    Dim y As New aSetTextCallback(AddressOf ReceivedText)
    Me.Invoke(y, New Object() {(Rohead)})
    Else
    Me.lblRobHead.Text &= Rohead
    End If

    but now my label display will change from:

    Robot is facing: ??
    Robot is facing: ??00
    Robot is facing: ??0000
    Robot is facing: ??000000

    and so on….

    I don’t know why 00 is added into the label
    and my rtbReceived.Text same like your example will display

    0
    00
    000

    again, zeroes are added inside….

  41. Martin says:

    Best Basic Tutorial of how to use the rs-232 class on the web

  42. Martin Murray says:

    Hello tiktakx

    I was hoping you could help me with a project I am doing.
    I need to be able to read in XML data through a serial port to a dataset and then bind it to my controls.

    I am able to read in the continues stream of XML data, and send commands to get stored XML data. I believe my program is treating all the XML as text and thats fine but i don’t understand how to bind it to controls. Either way i’d like to do it right and read it into a dataset and then bind it to controls within the delegate.

    Any assistance or tips would be most welcomed.

  43. Sitti says:

    Oh my goodness! This really helps me out.
    I am getting stuck almost 2 weeks with VB2010 rs232 interface.
    Thank you.

  44. paul says:

    Howdy,

    Great example… I’m getting an error on the reference:

    SerialPort1.

    The build error is:

    ‘SerialPort1’ is not declared. It may be inaccessible due to its protection level.

    I’m new to VB 2010 what am I doing wrong:)

    Paul

  45. paul says:

    I think that I figured it out I added the following line:

    Dim WithEvents SerialPort1 As New SerialPort()

  46. Bobby says:

    Hi,

    I cut and pasted the code but I get a whole bunch of errors. I don’t know why.

    Thanks for any help, will be greatly appreciated!

    Error 1 ‘Private Sub frmMain_Load(sender As Object, e As System.EventArgs)’ has multiple definitions with identical signatures. Form1.vb 3 17

    Error 2 Statement cannot appear within a method body. End of method assumed. Form1.vb 28 5

    Error 3 ‘myPort’ is not declared. It may be inaccessible due to its protection level. Form1.vb 30 9

    Error 4 ‘myPort’ is not declared. It may be inaccessible due to its protection level.Form1.vb 37 29

    Error 5 ‘myPort’ is not declared. It may be inaccessible due to its protection level. Form1.vb 38 31

    Error 6 Type ‘SetTextCallback’ is not defined. Form1.vb
    80 26

  47. Bobby says:

    Thanks Tiktakx

    I setup vb 2010 express as per the above example then copied and pasted the code. Then I tried to compile it but it has those errors.

    Thank You!

  48. Thanks. This was just the explanation that I have been looking for. Now, how would I transfer/append the output to a text file instead of to the text box? That way I could keep an entire log of my session.

  49. chew says:

    hihi
    may I know how to devlare serialport?
    it shows that serialport1. it not declared
    thanks

  50. Hi Tiktakx,
    Thank you for the example and lesson. I have been playing with the serial port console and have been getting mixed results. Now that I understand what was wrong with my code, I would like to know how can I capture/append the output to a text file. I would like to create a log of the entire session. Could you explain this to me?

    I tried posting earlier, but I do not see it below the last post on June 5, 2011.

    Thanks in advance

  51. chew says:

    hihi
    I have another question again
    Can I set the received Data is in integer only ?
    because if i set to string I received some extra symbol .
    so is it i just need to change the string to integer?
    sorry , I am newbie to VB . thanks

  52. vincent says:

    i was looking for something like this all year thank you so much i can honestly say I LOVE YOU. your awesome thanks thanks thanks.

  53. Mike Hewett says:

    I want to send and recieve Hex data . How do I change the code to recieve data in Hex ?

  54. Ludo Kustermans says:

    Hi,
    I implemented your SW, but get following error : AddressOf expression cannot be converted to object because object is not a delegate type.
    Can you please advise what this problem is / why you do not have this error with the same SW ?
    Thanks in advance
    Ludo

  55. Ludo Kustermans says:

    Hi,
    I was using the ode above, but found the error in the mean time. Forgot to add 1 line :
    Delegate Sub SetTextCallback(ByVal [text] As String)…it is solved.

    Thanks for your response
    best regards

  56. Mariano says:

    Hi. TKS for the code. Really smart people can translate tech to “human”. I tried to use it and I’m having trouble opening the port. I writte a couple of ifs with isopen and seems that the port opens but rigth away closes again. I use the old VB6 Comm on VB 2010 to confirm port is working and it is. So I must have some programming issue.

    Trendnet USB to RS232 device
    Port 3
    baudrate 2400

  57. Roel says:

    Hi,
    This is great. Good example with all the code. I followed the instructions excatly and it compiled the first time.
    Thanks for sharing this !!
    Best regards,
    Roel

  58. JONATAN ROJAS says:

    hi Tiktakx
    thank you for this example, it was very usefull to me.
    I want to know I need to recive a word of 16 bits in 2 segments recived. like the fisrt half sended first and then the second half. witch functions I need to use?

  59. Thai Tran From Vietnam says:

    thanks you so much. All best !

  60. syntaxerror says:

    thanks, very clear.. this is the best tutorial for serial commn.

  61. Gobar says:

    Hi Thanks for a great tut, It solved so many problems for me, However I need to get text that contains special char from the Swedish language, any tips of how to solve that? were using letters like an A with two dots over it (å,ä) and same thing with O (ö). How do I change char. settings for the richtextbox så that I get the whole word without replacing unknown characters with a ?

    Thanks

    /G

  62. tiktakx
    Thanks for the great tutorial. I have 3 questions:

    Q1. How do I stop the txt scrolling off the bottom of rtbReceived? I cannot find any property to stop this happening.

    q2. When I click btnDisconnect I wish to send 2 bytes to a motor controller to make sure the motors have stopped. The 2 bytes to then be seen in rtbReceived via the port loop-back. I think the port is closing too quickly but using sleep just locks up the form. Code follows:

    Private Sub btnDisconnect_Click(ByVal sender As System.Object,
    ByVal e As System.EventArgs) Handles btnDisconnect.Click

    SerialPort1.Write(SabertoothML_STOP & SabertoothMR_STOP & vbCr)
    Thread.Sleep(100)

    SerialPort1.Close() ‘Close our Serial Port
    btnConnect.Enabled = True
    btnDisconnect.Enabled = False
    End Sub

    Q3. Is there a VB joystick or pad that I can use on the form and control with a mouse pointer. Like a slider but in X & Y.

    Many thanks for your help.

    • tiktakx says:

      A1. try to remove the carriage return so it will not create a new line
      A2. try to Add Application.DoEvents to prevent the form from hanging
      A3. you could search for custom controls/ocx

  63. invictadeusvult says:

    Tiktakx

    Great tutorial many thanks

  64. Hi there, is there anyway to convert from ASCII to HEX?
    need some help here.. Thanks=)

  65. Billy says:

    I am using the following code to capture lines from the serial port (Com4):

    Public Sub MySerialport_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mySerialPort.DataReceived

    Dim strSTRBUFF As String = mySerialPort.ReadLine()
    ReceivedText(strSTRBUFF)
    Dim strtexttest As String = Trim((strSTRBUFF))
    Dim CALLPARSESUB As delSERIALDATAPARSE = AddressOf PARSESERIALDATA
    CALLPARSESUB.Invoke(strTEXTTEST)
    End Sub

    The sub CALLPARSESUB calls other methods in another form (call that form FORM2). Those methods then need to write text to the serial port.

    When the code in FORM2 is executed, the serial port has been closed. Adding the statement: frmMAIN.mySerialPort.Open()
    to FORM2 opens the port again.

    PROBLEM #1:

    When the first line is received by the serial port, the statement (in FORM2): frmMAIN.mySerialPort.Write(“X>N0A0” & vbCr & vbLf)
    is executed but nothing is sent to the serial port.

    PROBLEM #2:

    When a second line of data is received by the serial port, an error message is received the statement: frmMAIN.mySerialPort.open()
    is attempted for a second time FORM2:
    Access to the port ‘COM1’ is denied.
    Note: It is COM4 that is being used, not COM1.

    Can you help with what is happening and how it can be fixed?

    Thank you,

    Billy

  66. David H. says:

    This is excellent code! Thank you very much for posting this and it works perfectly. Maybe you can help me with a specific goal along these lines. I want to hook up a simple on-off relay to my machine and simply count the time between the on and off signal from the relay. Could you possibly help me with the code to make this happen? I would sincerely appreciate it. Thanks again, and have a Merry Christmas!

    David

  67. Rob Sobol says:

    I downloaded your SerialPortInterface.
    I imported it into Microsoft Studio Version 10.
    It loads fine.

    I connected my PC to another PC using a null modem cable. Using hyperterminal I can go to either keyboard, type and see the characters on the other PC.

    Using your program on my PC and hyperterminal on the other, I can use your SEND button and send text to the other PC and hyperterminal will display the characters. I cannot send from hyperterminal and see them in your program. I type on the remote PC, I see a delay in the characters being echoed back to the screen on the remote computer, but they never appear in your program.

    In debug mode, the SerialPort1_DataReceived routine does not appear to get called. It is like the event handler does not get raised.

    Can you get me on the right track?

    The code I am developing will need to keep reading in small chunks of data from the comm. port and send some back eventually.

    Thank you,

    Rob Sobol
    RSobol@HilightsInc.Com

  68. Rob Sobol says:

    Very odd. I put your Serial Comm program on the remote PC and it now communicates in both directions. Something is flaky when I tried to use Hyperterminal. I do not care about the details….it works.

    Thank you.

    Rob

  69. Ishtiaq Ahmad says:

    In Serial port properties, how to increase the value of DataBits from 8. for example if i want to set that value to 16 instead of 8…. can this b possible..?

  70. sundus says:

    i have connected my Pc with Pic and max232 via VB 10 using your code .what i send it displays in Receive Text box but its not burning on pic controller?What might be the reason

  71. Shashanka says:

    Your example was too good and clear. . .exactly the thing I was looking for. . .
    Special Thanks to you. . .you helped me do my project. . .

  72. sundus says:

    Thanks but do you think that i have to bootload the pic.i am using pic with max232

  73. sundus says:

    yes,but if we send the write command to pic and pic has the firmware in it then it wont work?or any other suggestion

  74. Rizk says:

    May I know how to fire a button event when a real world switch is pressed eventually the function behind the button on VB will perform the expected tasks? For example, when I trigger the physical switch , the webcam GUI created on VB will start capturing an image and recording videos.

    I am struggling with this part right now and I cannot seem to find any source about what I want on internet?
    Your help is very much appreciated.

  75. Rodrigo says:

    Nice example!Good job! Does this code works with USB ports?
    Thanks

  76. Rodrigo says:

    I’m working in a project that uses a PIC18F4550 and an USB-to-USB comunication.
    And I didn’t find anything that could work. I will make a test with your code.
    Thanks.

    • tiktakx says:

      If you are working on a USB HID project, this will not work, but if USB-CDC this will work

      You can also check microchip applications framework

  77. desmond says:

    hi tiktakx,

    First thanks for your kind share the code to public. this help me a lot. it work fine in my desktop application

    Currently i had a project that need to used serial port profile in compact framework (window mobile application).

    after i convert everything to window mobile form. the bellow code show me an error:

    cmbPort.Items.Add(myPort(i))

    //the target version of the .NET Compact Framework does not support latebinding.

    i had search and try to solve the error, but until now i still not get the solution.

    Kinly advice how can i solve for this? and any website or reference can provide? tq

  78. desmond kang says:

    hi, thanks because sharing… help my project a lot. I had testing this source code personally and it works. thanks a lot.
    currently i need to change the platform to window CE (to window mobile device). i apply the same code to the new platform, it show me the error bellow:

    cmbPort.Items.Add(myPort(i))

    //The targeted version of the.NET Compact Framework does not support latebinding.

    i search a lot from net, but i can’t meet the solution.

    Kindly advice, how can i solve for this or any website or link provide me to learn from there?

    Thanks in advance.

  79. chris30 says:

    Great job!

    I adapted your code to my project, when I type R, I actuates a motor which turns right and when I type L, I actuates the motor to the left on my picaxe 28×1 and it works “nickel”.
    When I type V (read a value from one of the A / D converters on my 28×1) I see appear in the rich text message box on my 28×1 : “DAC 1 VALUE :xxx” (value 0 to 255 max)
    it works fine but I would recover “only the value” and display it in a big label.

    I do not see how to do it from your code.

    if you could help me
    thank you in advance.
    (sorry for the translation but I’m French)

  80. Fs says:

    This is great! Thank you so much!

  81. This is a really useful example. Thank you so much. I’m using your program to read weight from a scale in my lab. I would like to create a feedback control loop with the readings. The scale transmits data continuously in a format “ASNG/W+169.50 kg” but the ‘169’ portion could become ‘ 69’ or ‘ 9’ or ‘ ‘. I’m trying to parse out the weight as a VB newbie, using messageBox.Show to test the parsing.

    The challenge is that as soon as I start using the messageBox, the [text] coming in gets long, like several readings concatenated with vbCrLf in between. So, I write my regex for what I see but then when I remove the messageBox the string is much shorter and rarely includes the entire weight so comes up Null most of the time.

    I think I need to maintain an array or a string and pop each value onto the end as I read it, and then parse out the weight each time from a 20 character string or so. Does this sound logical? Is it a common problem that you would have a code snippet for?

    Cheers!!!

  82. Jeff says:

    I get an error stating that SerialPort1 is not declared I am using VB Express is this a limitation or am I missing something

  83. mustafa says:

    first of all I am appreciated you for this article.
    but I have a problem.

    I have done everything you have said as seen image.
    Program could open the virtual serial port but when I click btnSend, the data does not appear in richtextbox.Where can be the problem?

  84. Quintus says:

    This is the first time someone took the time in showing the baby steps for rs232 use in vb 2010. I used it to display n string that is send from a weighing scale.With the same code how can i only display a certain part of string? The scale sends the string constantly. Looks like this(ww00000000kg), it then repeats it self.How can i only update the the string in stead of adding it constantly?
    Many thanks (ZS1QC)

  85. Hey thanks for the good tutorial, says:

    Hi there

  86. Beginner says:

    Hi there
    how can i test if the program runs proberly?
    it connects fine to another pc but i have no means to control what is sent there. As soon as I configure the hyper terminal on the other pc. I can’t connect anymore.
    When I try to connect to my mobile it works fine as well. But my phone asks me weather I want to allow the pc to use the phones internet connection.
    There might be an easy solution to that. But I have no clue.
    Many Thanks

  87. cheekang says:

    Quintus :
    This is the first time someone took the time in showing the baby steps for rs232 use in vb 2010. I used it to display n string that is send from a weighing scale.With the same code how can i only display a certain part of string? The scale sends the string constantly. Looks like this(ww00000000kg), it then repeats it self.How can i only update the the string in stead of adding it constantly?
    Many thanks (ZS1QC)

    hi i face the same problem. when i click send to other pc, it can show in the word richtextbox too…

    (but when i check with BlueSoleid, it show me i already revived from other device, but it can’t show me in richtextbox.

    Kindly advice.. where can be the problem?

  88. cheekang says:

    mustafa :
    first of all I am appreciated you for this article.
    but I have a problem.
    http://i43.tinypic.com/11t09c6.png
    I have done everything you have said as seen image.
    Program could open the virtual serial port but when I click btnSend, the data does not appear in richtextbox.Where can be the problem?

    hi i face the same problem. when i click send to other pc, it can show in the word richtextbox too…
    (but when i check with BlueSoleid, it show me i already revived from other device, but it can’t show me in richtextbox.
    Kindly advice.. where can be the problem?

  89. cheekang says:

    hi, tiktakx, thanks for the reply. sorry, i not understand it.
    em.. make sure that the receive event code is in the receive event of the serialPort that you add in your project???

    can give me more detail?
    very sorry about it.. i am very week and in this field

  90. cheekang says:

    if i only send “cytron, press any number” isn’t supported in sir program? thanks

  91. cheekang says:

    bellow is the code i get from cytron.

    //=============================================================================================
    //
    // Author :Cytron Technologies
    // Project :DIY Project
    // Project description :PR6-Bluetooth Remote Control
    // Date :21 May 2009
    //
    //=============================================================================================

    //=============================================================================================
    // Include file
    //=============================================================================================
    #include

    //=============================================================================================
    // Configuration
    //=============================================================================================
    __CONFIG(0x3F32);

    //=============================================================================================
    //Define
    //=============================================================================================
    #define seg PORTD // define 7 segment as PORTD

    //==============================================================================================
    // Function Prototype
    // User can write all the necessary function here
    //==============================================================================================

    unsigned char a;

    void init(void) // subroutine to initialize
    {
    SPBRG=0x0A; // set baud rate as 115200 baud
    BRGH=1;
    TXEN=1;
    CREN=1;
    SPEN=1;
    TRISD = 0b00000000;
    seg = 0b00000000;
    }

    void display(unsigned char c) // subrountine to display the text on the screen
    {
    while (TXIF == 0);
    TXREG = c;
    }

    unsigned char receive(void) // subrountine to receive text from PC
    {
    while (RCIF == 0);
    a = RCREG;
    return a;
    }

    //================================================================================================
    // Main Function
    // This is the main function where program start to execute
    //================================================================================================
    void main(void)
    {
    init();

    while(1) // Wait for ‘ok’ to be entered by user
    {
    a = receive();
    if (a == ‘o’)
    {
    a = receive();
    if (a == ‘k’) break;
    }
    }

    display(‘C’); // Text will display on Hyperterminal after ‘ok’ is entered
    display(‘y’);
    display(‘t’);
    display(‘r’);
    display(‘o’);
    display(‘n’);
    display(0x0a); //Go to new line
    display(0x0d);
    display(‘P’);
    display(‘r’);
    display(‘e’);
    display(‘s’);
    display(‘s’);
    display(0x20); // Space
    display(‘a’);
    display(‘n’);
    display(‘y’);
    display(0x20); // Space
    display(‘n’);
    display(‘u’);
    display(‘m’);
    display(‘b’);
    display(‘e’);
    display(‘r’);

    seg = 1;

    // wait for number and display it on 7 segment
    // The number display on 7 segment is depends on what number entered in Hyperterminal.
    while(1)
    {
    a = receive();
    if (a==’1’||a==’2’||a==’3’||a==’4’||a==’5’||a==’6’||a==’7’||a==’8’||a==’9’||a==’0′)
    {
    seg = a-0x30;
    }
    }
    }

    sir, can you give me some idea to trouble shoot, why i can’t received the word i send from my pic to my hyperterminal. tq

  92. Barry says:

    Hi, this code is brilliant by the way, it is just what I needed. Could you explain the received text code in a little more detail, I’m not totally sure what you did there! How would I change it if I wanted to receive the data as an int, and not in ASCII format?

  93. Ian Westbury says:

    Hi. Nice and simple and does exactly what I was looking for. I’m currently using a PIC16F628A to control a motors speed via the UART. I am going to try to add a chart control to look at real time speed against a set point.
    Thanks for the start!!

  94. RoGeorge says:

    Great tutorial.
    THANK YOU from Romania.

  95. DaveyMG says:

    Excellent tutorial, thanks! Helped me kick of my project to start communicating with my ELM OBD interpreter.

  96. faheem says:

    thankyou–so–much–man–you–are–great!

  97. Simon says:

    >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

    You may find that the .ReadExisting() method of the serialport object behaves unpredictably.

    Try replacing it with the .ReadLine() method.

  98. cvan says:

    hai….im trying to find how to control 8051 using vb2010 by serial communication…do any wan have any idea….plzz help mee

  99. Joe says:

    Many thanks for the code and explanation. You have saved me alot of time by providing the quickstart VB tutorial for the com port.

  100. Mike says:

    Can you email the code to me ? I can’t find a download link.

    Thanks,

    Mike

    • tiktakx says:

      Mike
      I think you are the only one that cannot find the link, thousands have downloaded the project file on the link posted on the end part of the tutorial

  101. PT says:

    Many thanks, I’m a VB total novice and this saved me a lot of time. I have one question, though. The combo boxes do not populate with available ports and baud rates, and the Disconnect button is not disabled at startup. From which I presume Sub frmMain_Load is not being executed. What could cause that? Everything else works fine.

  102. PT says:

    I should add I’m using VB 2010 Express on W7.

  103. DavidSG says:

    Thank you tiktakx for a good example. This gave me a good leg up on switching from VB6 to VB2010. Serial comms is crucial to everything I do.

    I few comments and extensions to the example, which may help others who follow.

    * Copy/pasting your original sample code into VB2010 seemed lose the “Handles” bit of several event handlers. No idea why, but I had to enter them back in manually.

    * I replaced your “IO.Ports.SerialPort.GetPortNames() ‘Get all com ports available” which populates the port selection combox with unfriendly COMnn numbers, with code that provides friendly names like “USB to serial adaptor (COM255)”. I got the code by digging around on some other sites. Here it is:

    Try
    Dim searcher As New ManagementObjectSearcher(“root\cimv2”, “SELECT * FROM Win32_PnPEntity”)
    Dim obj As String
    For Each queryObj As ManagementObject In searcher.Get()
    obj = queryObj(“Name”).ToString
    If InStr(obj, “(COM”) Then
    Debug.Write(obj)
    If Strings.Left(obj, 2) “BT” Then ‘Omit bluetooth ports (many on my laptop)
    cmbPort.Items.Add(obj)
    cmbPort.Text = “(COM255)” ‘My choice of default (convenient for me)
    Debug.Print(” pass”)
    Else
    Debug.Print(“***** Dump ****”)
    End If
    End If
    Next

    Catch err As ManagementException
    Debug.Print(“An error occurred while querying for WMI data: ” & err.Message)
    End Try

    I don’t understand it all, but it works – on my computer at least. My computer’s Device Manager reports about 15 Bluetooth COM ports, so the above code filters them out. It also requires reference to System.Management, and a line right at the top:

    Imports System.Management

    (I am too new with VB2010 to yet know exactly ho to correctly make referebnces like that, so I just banged around until it worked!)

    The above code will populate the list with names that are user friendly but break the

    “SerialPort1.PortName = cmbPort.Text”

    statement. Therefore I added a function that converts the friendly name to the unfriendly version:

    SerialPort1.PortName = ExtractPortName(cmbPort.Text)
    …..

    Private Function ExtractPortName(ByVal FriendlyName As String) As String
    Dim i As Int16
    i = InStr(FriendlyName, “(COM”)
    If i > 0 Then
    FriendlyName = Mid(FriendlyName, i + 1)
    i = InStr(FriendlyName, “)”)
    If i > 1 Then
    Return Strings.Left(FriendlyName, i – 1)
    End If
    End If
    End Function

    I found [text] (in sveral places in th eprogram) really confusing. Being a newbie means one significant concept at a time is all my poor exploding head can cope with. So after some more googling I replaced [text] with RxString (a name that does not conflict with a reserved word.) IMHO this makes the program more readable – for a newbie.

    There is another way of using friendly names here:
    http://social.msdn.microsoft.com/Forums/is/Vsexpressvb/thread/3f19675a-6968-4800-823e-bdec5327312e
    In that post is an offer of an alternative EnhancedSerialPort.dll that will return friendly names directly via an alternative method .GetPortDescriptions() At the moment I am reluctant to be playing with anything too far outside MicroSoft box, so I haven’t used it. (Long term updates would be an obvious problem)

    This example also forced me to start learning about threading and delegates. I found a good explanation at
    http://visualbasic.about.com/od/usingvbnet/a/delegates.htm

  104. phann says:

    Hi tiktakx,

    thank you very much for your tutorial, it help me a lot.. because I’m still newbie in vb.net and micro controller. it really save my time..

    I want to ask something about a several code that you write, as below:

    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

    could you explain me of how those code works.
    in my case I’m not using RichTextBox but only just using a variable As String. i Try modified your code without using RichTextBox but it always got an error.

    could you help me out, to fit in my case.

    Thx in advanced,
    Phann

  105. DavidSG says:

    Another thing: Pure binary data

    I spent today discovering how to reliably get binary data in and out of the serial port. In other words, getting all 256 binary codes that can be represented in a byte to be passed through SerialPort without corruption. I started with the above example. What I discovered is that under certain conditions codes &H80 and above may be corrupted, more often or not changed to &H3F. I was using one of my company’s controllers ( http://splatco.com ) the other end, with a program that would sometimes send me stuff, sometimes receive and action stuff and sometimes simple echo characters (all depending on some input switches).

    My conclusion (a result of much googling!) is that you need to execute the following two lines when opening SerialPort:

    SerialPort1.Encoding = System.Text.Encoding.GetEncoding(1252)
    Thread.CurrentThread.CurrentCulture = Globalization.CultureInfo.InvariantCulture

    The first line is totally essential. The second sometimes makes a difference, sometimes not. I tested this as hard as I could with the localisation set to a number of different countries (Control Panel>Region and Language>Formats in Win7). With both lines present I could not make it fail. My final program sends out every possible code and checks every return, reporting any errors.

    I tested on just one computer under Win7. I will be testing on other machines and other operating systems, real and virtual.

    BTW, I have been programming serial ports since the 1970’s, on DOS and before. Micro$oft have NEVER got it 100% right. .NET’s SerialPort seems to follow this established tradition!

    • Tamer says:

      Hi there
      Thanks for your nice feed back and I am interested to share with you my experiance with this program
      I am interfaceing to medical equipment that sends ENQ and wait for ACK but the ENQ does not appear correct in the text box, it appears as , I haghly appreciate if you can help me
      tamer_elassal@hotmail.com

  106. PT says:

    I have never been able to get this code to run. As soon as I connect the loopback jumper and receive a character, it crashes with the following message:

    “FatalExecutionEngineError was detected”

    “The runtime has encountered a fatal error. The address of the error was at 0x6db83a56, on thread 0x1818. The error code is 0xc0000005. This error may be a bug in the CLR or in the unsafe or non-verifiable portions of user code. Common sources of this bug include user marshaling errors for COM-interop or PInvoke, which may corrupt the stack.”

    I take it this is one of the threading errors the “delegate” statement was supposed to prevent? I tried it on three different computers, one XP and two W7, each with a fresh installation of VB 2010 Express. I can run equivalent code in VB6 with no problems at all.

  107. Vijay Kumar says:

    Really helpful. I am searching for this article a long time for my client. Thanks at all.

  108. […] Visual Express 2010 Environment I've written the codes below, based on the tutorial at this site. Tutorial Site as well as this microsoft website for reference (putting it here just in case) MSDN Serial Port […]

  109. Alex says:

    This is excellent, and has certainly saved me so much time. I have a question. Is there any way to automate the transmit data process? I need to get the results every 15 minutes from a device connected to the serial port. Is this possible?

  110. TNgoc says:

    your code continuously check for new data sent to PC right ?,
    I set up an MCU continuously send ‘a’ to COM, the hyperTerminal work great, but your code does not show anything out. baud rate and comport are kept the same

  111. Ailada frm thailand says:

    I got problem at. Settextcallback on Receivedtext private sub . When I debugging It show undefine type of settextcallback

  112. Robert Wagner says:

    I am learning Visual Basic 2010, using Visual Studio 2010. I have a frmMain that has buttons to call various other forms – frmSetup, frmLapClock, frmStopWatch, etc…
    I would like to initialize and declare my Serial Port once (load settings from txt file), then be able to use it in all of the forms. This includes frmSetup where I can test and change to port settings if needed. While I can do this during the formLoad process of the frmMain, I cannot reopen the port in sub forms. I tried making the Serial Port public and a variety of other methods. I typically drag the serial port icon from the toolbox into the frmMain. Also tried manually setting it up by typing in the commands + setting up a separate module.

    I am familiar with setting this up on one form and had success with that – many example available on the web.
    Any help would be greatly appreciated.

    RW

  113. Tamer says:

    I have a problem with this program , I am using it to recieve data from serial port connected to a lab analyser but this program can not read ASCII control character, the analyser is sending and I am recieving this  on the program
    how can I translate this to a normal text to read, please help

  114. Jeff says:

    Thank you, works great. The problem I am having is that instead of using the Transmit Data box I am sending a hard coded string which works fine until I try to send a second one immediately after the first, then instead of reading and then sending the second string, it tries to send all three at the same time. All of these work individually or from the Transmit Data box. example:

    SerialPort1.Write(“CONNECT ON” & vbCr) ‘This always has to be sent first, I get a prompt
    back
    SerialPort1.Write(“LISTLOG” & vbCr) ‘This returns a list of log file of incidents & results
    SerialPort1.Write(“REVISION” & vbCr) ‘This sends back data about the software revision

    Can you please provide a solution?

  115. ACTKK says:

    Thanks in advance:
    The code is building ok, but i cant get to populate the cmb´s, baud rates and COM ports. I am using a Prolific USB to rs232, and the device manager (win 7) shows it installed in COM4.
    Any suggestions?

  116. ACTKK says:

    Sorry, my bad in the previous question, i already solved it.
    I am currently communicating with a PIC16f877a, with a few issues:
    Sometimes, lines incoming from the pic appear in the “received” textbox twice, and it seems that when i send some data, it is sent twice too. If i use the normal hyperterminal this does not happen. Thanks in advance.

  117. vaishnu says:

    Getting an error as InvalidOperationException: port is closed
    Error in the line:
    SerialPort1.Write(txtTransmit.Text & vbCr)

  118. Chris says:

    Excellent example code. Thanks for sharing.

  119. mike says:

    Cutting and pasting the entire code (and only )into visual studio 2010 VB on a win 7 64 bit laptop I get a notice about the cmbPort (little red marker) everywhere in the code where cmbPort is.
    It says : ‘cmbPort’ is not declared. It may be inaccessible due to its protection level.
    There are four corrections to choose from. If I pick the first “Generate method stub for cmbPort in SerialPortInterface.frmMain.
    The red markers go away but end up with this code which doesn’t match yours???
    Private Function cmbPort() As Object
    Throw New NotImplementedException
    End Function

    Whatz up here?

  120. mike says:

    Well should have kept working on it before posting. Must have done something in properties by accident when changing the name of the combo box for the port. I deleted and recreated the cmbPort and no red markers. Sorry. Code is fine on this site, my fingers are not.

  121. nikka says:

    Hi. What if the data from the serial port needs to be graphed in VB 2010?

  122. I am trying to talk to an RS232 interface on an Hameh 1024 oscilloscope but Id do not get a reaponse. The RS232 link to the oscillocsope does work with the screen dump software provided by the manufacturer but not with the code described.

    How can I confirm that the link is working from the VB software?

    I am running VB10 and WindowsXP.

    Any other suggestions?

    Thank you.

  123. C.K says:

    Thank you so much. This program is awesome.

  124. I used this tutorial and it has worked great, however on of my devices i am trying to connect to require “?” to ping it to get the response. Each of the other devices i have tested this with works well except this one. Is there an issue sending “?” to the device with this program.

  125. Alessandro says:

    Thanks a lot for this excellent code!!
    I’m trying to modify it to make my form send different strings to a serial port clicking on different buttons. I need to read the port and write answers in different textboxes, instead of only one rtbReceived tex box.
    How can i modify the ReceivedText sub to do this ??
    ——-
    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
    —–
    Thanks,
    alex

  126. Richard says:

    Will this RS232 Terminal build ok with VB 2012 (Microsoft Visual Studio)
    TIA

  127. Richard says:

    Managed to compile it with VB 2012. Debugger stopped with.
    A first chance exception of type ‘System.ArgumentOutOfRangeException’ occured in System.Windows.forms.dll Don’t know why this error comes up but it works great.
    Thank you for your efforts putting this exercise together.

  128. nsypid says:

    Thanks. Really helps

  129. Bobi says:

    Hello,
    Thanks very much for this sample.
    I have just a problem when i send a String , the first time i receive only the 1st character.
    If i click again on SEND button, i receive the complet String.

  130. Gerald says:

    Hi Really excellent like everyone says! One small bug I found when receiving streamed data. I have 30 chars per line of data coming in at 50hz constantly. I use “ReceivedText(SerialPort1.ReadLine()) instead of readexisting so I get clean lines. I also changed the text box so it overwrites each line – other wise it just fills up too much.

    Bug is – If I click disconnect while data is being received I often get this error. “The I/O operation has been aborted because of either a thread exit or an application request.” at ReceivedText(SerialPort1.ReadLine().

    Is there a preferred way to trap this? I have used try /catch with a msg warning if the error occurs – this seems to handle it – but sometimes i just get a crash with no information – just a freeze – though maybe it’s unrelated?

    Thanks fro your help..

    • Gerald says:

      Hi

      I solved the bug which causes error on disconnect by changing this section :

      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

      instead of “Me.Invoke(x, New Object() {(text)})” I put ” Me.BeginInvoke(x, New Object() {(text)})”

      I hope this is useful… 🙂

  131. Roger says:

    This program is awesome, this application almost same like a hyperterminal thank for provide the coding.
    Have reference to do the input & output and do the graph at VB by using PIC18F4550.

  132. ahmed says:

    thank u for the program , i try to write this in data recive but there is eror

    private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
    SerialPort1.BaudRate = 9600
    SerialPort1.Parity = Parity.None
    SerialPort1.StopBits = StopBits.One
    SerialPort1.DataBits = 8

    Dim x As String
    x = SerialPort1.ReadExisting()
    TextBox1.Text = SerialPort1.ReadExisting()

    how can i recive data without clik button

  133. bimb says:

    hi tiktakx,

    Nice job you do here…..i have learnt from you.

    please what code do i write to be able to plot a line graph of the received data.

    please help with this too.

  134. You actually make it appear really easy with your presentation however I in finding this matter to be actually something
    that I believe I might never understand. It kind of
    feels too complicated and very huge for me. I am having
    a look ahead on your next publish, I’ll attempt to get the hang of it!

  135. stenbj says:

    Hi there,
    I downloaded and tested tis 6 months ago with a looped RS232 and it worked fine.
    Now I want to connect an AVR chip for which I plan to get a USB to SPI converter. The SPI is on
    the AVR chip and easy to use. Can this serial software work from Pc USB to the USB ?
    The chip I planned to use is Microchip MCP2210. This avoids the special cable USB to Rs232 and special voltages at the RS232 end. Thankful that the page is still alive. Great job!

    • tiktakx says:

      Yes this will work with MCP2210 you just have to check what com port it will be installed in your system

      • stenbj says:

        Hi tiktakx, thank you very much for useful reply !
        Is the chip I proposed very suitable for this job ? After searching again I found “too many to go through” that could be candidates. The main thing is seamless background USB installation so that after that at least one character at a time can be sent, similar to RS232.
        For instance I had in mind the device would be a slave but it looks like a master which I think means that I need to set up an interrupt for the operation ?

  136. khaoula says:

    please can u help me i want to receive information from a terminal connected to my comupter with serial port rs232 and read it on my vb.net2008 pleaaaaaaaaaaaaaaaaase heeeeeeeeeeeeelp 😥

  137. Hi,
    First of all, I would to thank you for your help allowing us to use your sample code. I am currently using your example to enter Part number to a device, my device has the following internal commands for entering P/N and S/N. [c8 xxxxxx] and [caxxxxxxx]. where c8 & ca are device internal commands and x are P/N & S/N. Sometimes users forget to add the c8 or ca when they’re entering it in the “Transmit Data” box. I wanted to know whether I could preset or include the internal commands in the source code above, so when the user is entering the P/N or S/N they just have to type in Transmit data box just the part number as (1121225).
    Any help from anybody would be greatly appreciated, and keep up with good work.

    ********************************************************************************************************
    Is it possible to set the either characters [c8 ] or [ca] in place txtTransmit in the portion of the code below?
    *************************************************************************************************************

    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

    Thanks,
    Will

  138. Tiktak,

    I just wanted to say thank you for sharing your skills and knowledge with us, I have used your example with some modification to meet my need and it works. Thank you once again

    WJ

  139. Ajinkya says:

    hi….

    I have developed above project by referring this tutorial. I want to use Bluetooth module. But i am facing problem when i click on send button. I have set proper COM port and baud rate (115200) but whenever i click the send button, the application hangs and needs to be close from task manager. Actually i am sending the data only thru bluetooth dongle connected to PC, but i have no any receiver module yet. Is this problem, that receiver is not available…???

  140. Matt says:

    thank you for your code but I am having a problem with it.
    I am using:
    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

    When I run the code and hit the “Print” button on the scale the correct amount shows in the rtbReceived.text. BUT after that I can not do anything with the rtbReceived.text value. If I do I get an error “Cross-thread operation not valid :Control rtbReceived accessed from a thread other than the thread it was created on”
    What do I need to do so I can use the data from the rtbReceived????
    Thank you
    Matt

  141. Matt says:

    I am having a problem with your code not grabbing all the data. So instead of getting 5.337 lb I will get 5.3 or 5.337 or 5.337 l
    Can you tell me why this is happening?
    thank you
    Matt

  142. Titano says:

    Hi Tiktak,

    Very excellent piece of work.
    Its running perfectly for me except for one thing.

    I do not get a response from the device at all.
    I connected a chamber to my PC thru the RS232 cable.
    I checked all connections, seems fine.
    The connections goes this way :
    Chamber>>RS-435>>RS-435 to RS-232 Converter>>RS-232 USB Adaptor>>My PC

    When I typed in my commands of the chamber, i do not get any response.
    Why is that so?
    Pls advise

    Thanks
    Titano

  143. tony says:

    hi,
    how to show the last value of richtextbox to a label or a textbox? i want to show for the real time.for the scale weiight

  144. Thank you Very Much .. i haven’t tried this code but i will .. i was really struggling for such details ..thanks

  145. abhi says:

    hi
    first thank you for this great tutorial, i did everything as per the instruction. But “build serialinterface” is not appearing on my visual studio 10 in debug option. and further does usb can be used as com port?

  146. Ryuu says:

    Thank you very much sir, but I have one problem with Serial Port.
    I am using a modem and want to check it’s signal. I use command “AT+CSQ”.
    And replied “+CSQ: 16,99” then, how am I can only get the number 16 only? Exclude the “+CSQ” and “,99” from the string.

  147. ryuu09 says:

    Could you upload the project source again? It seem that the one you uploaded before is deleted or something. Thanks before.

  148. Fiddule says:

    Thanx dude for make this it’s really helpful to me

  149. stenbj says:

    Hello Tiktak,
    New problem with Windows 8…
    No serial ports are detected.
    I am using USB to RS232 converter whicj is coming up as com 16 in USBDview (free software to view all USB devices status)
    I have also installed it and no difference. On XP it was just to use it.
    It is the statement: myPort = IO.Ports.SerialPort.GetPortNames()
    followed by: maxp = UBound(myPort) that gives maxp = -1 which is none found…

    All help much appreciated !
    Sten

  150. Fatma says:

    i try it but i have nothing in the outputbox

  151. Fatma says:

    i want to do the same work but using a VIRTUAL serial port , how can i configurate it ?

  152. Valentino says:

    Thank you so much for this tut, it’s been quite helpful.
    I used the code and every part of it worked as it should, but I needed to tire the received data to specific variables, like in a system test situation where you set the values of different input variables and read the output status. so I decided to have labels named after these output status and instead of RichTextBox inside the GroupTextBox I replaced it with different TextBox named after these specific output status.
    It’s been quite challenging and frustrating to get these values in their rightful positions / locations.
    I’m very new in this environment visual basic, few day old experience. I will so much appreciate any help I can get to enable me resolve this.
    Thank you once more.

  153. nichoma says:

    there is an updated code , with dynamic port selection and on off switch refer this page http://www.computeraidedautomation.com/arduino/vb-net-and-arduino-port-selection-combo-box/

  154. mohd shanab says:

    this is realy good but i want to read data from serial port RS232 from another PC transfering to excel sheet

  155. Montani Antognio says:

    In the serial port interfacing with VB.Net 2010 project how do you insert a photocell to shorten the TX and RX pin so that it acts as a Send button.

  156. Luis Carlos Hermosillo Lara says:

    I’m running under Visual Studio 2015 and not recieve response text. The “Recieved Data” is nothing

Leave a reply to doki doki Cancel reply