7 Replies - 9154 Views - Last Post: 16 August 2012 - 01:14 PM Rate Topic: -----

#1 andicom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 14-August 12

Serial Port communication with VB.Net (Ports don't show up)

Posted 14 August 2012 - 04:22 PM

Hi guys, 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.
Tutorial Site

as well as this microsoft website for reference (putting it here just in case)
MSDN Serial Port Class reference

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. Are my codes somewhere wrong? or is it my computer? Please show which part is the error
2. Is there anyway to beutify the codes? (make it shorter, simpler, that would be nice)
3. 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! :D
Error Messages and 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



Is This A Good Question/Topic? 0
  • +

Replies To: Serial Port communication with VB.Net (Ports don't show up)

#2 AdamSpeight2008  Icon User is offline

  • MrCupOfT
  • member icon


Reputation: 2270
  • View blog
  • Posts: 9,496
  • Joined: 29-May 08

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 14 August 2012 - 04:25 PM

What's preventing you including or copying and pasting the 2 errors messages in the contents of the post?
Was This Post Helpful? 0
  • +
  • -

#3 andicom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 14-August 12

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 14 August 2012 - 04:59 PM

Previously it shows some error.. "You are not allowed to use that image extension on this board. "

I figured it must be the shorting url thing, so I take the actual link. Link might not work after sometime, I think? However, the dropbox file will stay there. Thanks anyway for the heads up

Serial Port
Posted Image

Errors at debugging
Posted Image

Errors running the binaries
Posted Image
Was This Post Helpful? 0
  • +
  • -

#4 andicom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 14-August 12

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 14 August 2012 - 10:23 PM

I posted the link to the image here.
http://postimage.org/image/loo54h54h/
http://postimage.org/image/wqyne0u2p/
http://postimage.org/image/rak5vjjtl/
Was This Post Helpful? 0
  • +
  • -

#5 andicom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 14-August 12

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 16 August 2012 - 06:55 AM

Anyone can help?

I'm clueless now. Btw, a working tutorial for serial ports communication with windows form using Microsoft Visual Basic 2010 is also appreciated. I've tried one or two, just not comprehensive enough to get them work...
Was This Post Helpful? 0
  • +
  • -

#6 Ionut  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 385
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 16 August 2012 - 07:35 AM

The error is quite self explanatory. You cannot assign an empty string to PortName property. As I see from the code, this happens because the combobox that should have all the port names from the system is empty. The reason?
  If myPort.IsOpen = True Then  
     cmbComPort.Items.Add(port_name)  
  End If  


You don't open anywhere the port, you just initialize an object. By default, a serial port is closed until you open it.
Dim myPort As New IO.Ports.SerialPort(port_name) 


To open a port use, Open method.
As an advice, you should add port_name to your combobox and trap any errors when you try to use one of the items.
Was This Post Helpful? 0
  • +
  • -

#7 andicom  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 6
  • Joined: 14-August 12

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 16 August 2012 - 07:51 AM

Thanks. I get that now. So the below codes should give me the available port, right?

'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


Just to be sure, I tried simple codes from MSDN as below

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

however, my code above still says the array myPort is empty. what didnt work?
btw, I dont really get this part

"As an advice, you should add port_name to your combobox and trap any errors when you try to use one of the items."

Mind to clarify? Thanks
Was This Post Helpful? 0
  • +
  • -

#8 Ionut  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 385
  • View blog
  • Posts: 1,057
  • Joined: 17-July 10

Re: Serial Port communication with VB.Net (Ports don't show up)

Posted 16 August 2012 - 01:14 PM

Quote

however, my code above still says the array myPort is empty. what didnt work?

I see from your code that myPort is not an array, it's a variable of type SerialPort. And to clarify your code.
 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


You don't need line 2. There you just initialize an object you don't need(and don't use). GetPortNames returns an array of strings with the names of the serial ports found in the registry. So, in that for each all you have to do is to add the name found in GetPortNames to the combobox. This is the part where i try to explain myself better

Quote

"As an advice, you should add port_name to your combobox and trap any errors when you try to use one of the items."

Any COM port can be used by a single application at a time. Your initial code would verify if the COM port is opened and in case of a true statement, you would add it to the combobox. So I thought that you want in that combobox only those ports that can be opened and not kept busy by another application.
So, my advice would be : add all your ports no matter the state(busy or not) and when the user tries to open a conversation(=opens a port) you will catch the exception and prompt it
public sub ConnectButtonclick(sender as object, e as EventArgs)
  
   Try 
      someSerialPort.Open 'if the port is busy, this will raise an error
      'if not open, do some stuff here
   catch ex as Exception 
      MessageBox.Show("This port cannot be opened. Probably busy or configured incorrectly")
   end try
 end sub



In conclusion, your code should work, but the result is in the combobox and not in myPort variable.
Was This Post Helpful? 0
  • +
  • -

Page 1 of 1