Vb.net – Serial Port Communication using VB.Net (Ports dont show up)

serial-portvb.netwinforms

first of all I'm not very good at programming and I've tried to be as explanatory as possible in my codes. I've been trying to write a program which enables a user to chat (recieved & transmit) messages via Serial Port using a simple custom made IR modem. I've constructed the modem and now trying to write my own simple program instead of using Terminal or other already written program (i.e. Tera Term). Btw, I'm on Windows 7 and using the Microsoft Visual Express 2010 Environment

I've written the codes below, based on the tutorial at this site.
(putting it here just in case)
MSDN on Serial Port

Problem (as of now)
The combo boxes cmbComPort doesn't seem to catch any available ports on my computer. I suspected that probably there is none! So I checked and here is what I found. Based on this, I assume there is a Serial Port on my computer and hence this is not the source of the problem (Let me know otherwise, because I'm not really sure). I run the debug and an error message popped out. I then build the program to test it out. Both error messages are attached below

Questions
1. Seems like the codes below doesnt catch the available ports and store them in the myPort array.

'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        If myPort.IsOpen = True Then
            cmbComPort.Items.Add(port_name)
        End If
    Next

I wondered if the port itself is problematic and wasnt detected. However, using codes below, I was able to confirm that COM1 exist and working.

Imports System
Imports System.IO.Ports

Module SerialPortExample

Sub Main()
' Get a list of serial port names. 
Dim ports As String() = SerialPort.GetPortNames()

Console.WriteLine("The following serial ports were found:")

' Display each port name to the console. 
Dim port As String 
For Each port In ports
    Console.WriteLine(port)
Next port

Console.ReadLine()

End Sub 
End Module

Here is what the console output –

The following serial ports were found: COM1

So, the port is there. The problem probably lies (I'm not entirely sure anyway) on this part of the codes?

'procedure to detect all available ports and store them in the myPort array
For Each port_name As String In IO.Ports.SerialPort.GetPortNames
    Dim myPort As New IO.Ports.SerialPort(port_name)
    cmbComPort.Items.Add(port_name)
Next

Is there anyway I can check the content of myPort array after this line? as well as the items of cmbComPort?

One more thing, this is a project which accepts any extra features (writing my own program is definitely one of it). I could appreciate if you guys can drop any ideas on the features, whether related to the serial port communication or the program interface itself. I can think of a few, such as Save Chats to file, Load Chat files, Help/Tutorial file – all are to be implemented once I figured the above error. Moreover, I was thinking is there anyway I can draw a 'bubble chat' to display the conversations instead of plain rich text box? that would be nice.

Thanks in advance! 😀
Project files

CODES:

'Chatty Raffy Version 1.3
'This is a simple program to demonstrate Serial Ports communication via a simple custom made IR Modem. 

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports

Public Class frmMain

Dim myPort As Array  'an array to store list of available ports

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)

    'Fill up the cmbBaudRate Combo box to common baud rates used
    cmbBaudRate.Items.Add(9600)
    cmbBaudRate.Items.Add(19200)
    cmbBaudRate.Items.Add(38400)
    cmbBaudRate.Items.Add(57600)
    cmbBaudRate.Items.Add(115200)

    'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        If myPort.IsOpen = True Then
            cmbComPort.Items.Add(port_name)
        End If
    Next

    'initiate the combo boxes
    cmbComPort.SelectedIndex = 0  'set cmbComPort text to the first COM port detected
    cmbBaudRate.SelectedIndex = 0    'set cmbBaudRate text to the first Baud rate on the list
    cmbParity.SelectedIndex = 0    'set cmbParity text to the first Baud rate on the list
    cmbStopBit.SelectedIndex = 0    'set cmbStopBit text to the first Baud rate on the list

    'btnDisconnect.Enabled = False   'disable the disconnect button

End Sub

'open the selected serial port and start the connection
Private Sub btnConnect_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
    SerialPort1.PortName = cmbComPort.Text      'set Serial Port to the selected COM port 
    SerialPort1.BaudRate = cmbBaudRate.Text      'set Baud rate to the selected value Baud rate
    SerialPort1.Parity = cmbParity.Text     'set parity setting to the selected value 
    SerialPort1.StopBits = cmbStopBit.Text  'set stop bit setting to the selected value

    SerialPort1.DataBits = 8    'use the default 8 bit for data bit length

    SerialPort1.Open()      'open the chosen serial port

    btnConnect.Enabled = False      'disable the Connect button
    btnDisconnect.Enabled = True    'enable the Disconnect button
    picboxDisconnect.Visible = False 'disable the disconnect picture
    picboxConnect.Visible = True 'enable the disconnect picture
End Sub


'close the serial port currently in used, hence closing the connection
Private Sub btnDisconnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnDisconnect.Click
    SerialPort1.Close()     'close the used Serial Port

    btnConnect.Enabled = True  'esable the Connect button
    btnDisconnect.Enabled = False  'disable the Disconnect button
    picboxDisconnect.Visible = True 'enable the 'disconnect' picture
    picboxConnect.Visible = False 'disable the 'connect' picture
End Sub

'send the text contained in the txtText to the serial port in ASCII using the 'SEND' key
Private Sub btnSend_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
    SerialPort1.Write(txtTransmit.Text & vbCr)
End Sub


'detect data at the serial port and call ReceivedText automatically 
Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
    ReceivedText(SerialPort1.ReadExisting())
End Sub


'read incoming messages at serial port once data is detected
Private Sub ReceivedText(ByVal [text] As String)
    'compare 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



'this section prevents user from making any changes to the current connection without disconnecting

Private Sub cmbComPort_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs)
    If SerialPort1.IsOpen = False Then
        SerialPort1.PortName = cmbComPort.Text
    Else
        'pop an error message if user try to change port without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub


Private Sub cmbBaudRate_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.BaudRate = cmbBaudRate.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

Private Sub cmbParity_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.Parity = cmbParity.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

Private Sub cmbStopBit_SelectedIndexChanged(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles cmbBaudRate.SelectedIndexChanged
    If SerialPort1.IsOpen = False Then
        SerialPort1.StopBits = cmbStopBit.Text
    Else
        'pop an error message if user try to change Baud rate without closing the current port in use
        MsgBox("Please close the currently used port before making any changes to the connection setting", vbCritical)
    End If
End Sub

End Class

Best Answer

Allright, I did have missunderstanding of what it means by a port is 'open' or 'closed' before, and was pointed by my friend. Since then I fixed that part of the codes to

    'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
    Dim myPort As New IO.Ports.SerialPort(port_name)
        cmbComPort.Items.Add(port_name)
    Next

@hans : Actually the circuit already work using the terminal IR modem (coming with windows) at lab's computer. And I have confirmed using this codes that in fact, the serial port does exit and working

Imports System
Imports System.IO.Ports

Module SerialPortExample

Sub Main()
    ' Get a list of serial port names. 
    Dim ports As String() = SerialPort.GetPortNames()

    Console.WriteLine("The following serial ports were found:")

    ' Display each port name to the console. 
    Dim port As String 
    For Each port In ports
        Console.WriteLine(port)
    Next port

    Console.ReadLine()

End Sub 
End Module

Here is what the console output -

The following serial ports were found: COM1

So, the port is there. The problem probably lies (I'm not entirely sure anyway) on this part of the codes?

'procedure to detect all available ports and store them in the myPort array
    For Each port_name As String In IO.Ports.SerialPort.GetPortNames
        Dim myPort As New IO.Ports.SerialPort(port_name)
        cmbComPort.Items.Add(port_name)
    Next

Is there anyway I can check the content of myPort array after this line? as well as the items of cmbComPort?

Related Topic