1
votes

I am working on a project where RS232 is connected via USB port of laptop / PC. I already created the vb.net application. As the application loads for the first time, it needs to detect the serial port. As of now, I manually put the portname in the properties of the serialport but if I deploy my application and if I use other laptop / PC, there would be an error: System.IO.IOException as I run my GUI. I want to program the automatic detect of serialport but I am new to serial port programming in vb.net.

Can anyone help me? thanks!

This is some part of my program:

Imports System.IO.Ports

Public Class Form1

'Dim myPort As Array 

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
    Try

        'myPort = IO.Ports.SerialPort.GetPortNames() 

        SerialPort1.Open()
        Timer1.Enabled = True
    Catch ex As Exception
        MsgBox(ex.ToString)

    End Try
End Sub

Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived

    '==zigbee sent data to the app====
    Console.Beep(3000, 1000) 'high tone buzzer whenever there is a notification received

    MsgBox("THERE IS A NOTIFICATION RECEIVED!")

    uart_rx = Me.SerialPort1.ReadExisting
    toDisplay = toDisplay + uart_rx

    flag = 1 'there is a notification sent


End Sub

....

After myPort = IO.Ports.SerialPort.GetPortNames() , I don't know what to do next.

2
Will this work: While (counter = 0) SerialPort1.PortName = myPort(i) SerialPort1.Open() If SerialPort1.IsOpen Then counter = 1 End If i = i + 1 End While counter = 0 Err my cable is on bad mood hehe cant detect my PC. - Catherine Takishima
How would you know if there is a device connected or not? Does it send data continuously? Does it respond to a specific command? - dbasnett

2 Answers

0
votes

There is an example showing how this is done on the following webpage: http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.aspx

In the example the user is prompted for the serial port settings before the application communicates with the port.

SerialPort.GetPortNames (http://msdn.microsoft.com/en-us/library/system.io.ports.serialport.getportnames.aspx) will get the names of the serial ports.

0
votes

I provide a Listbox and populate it with all ports on the system. User has to select the com port, after which you assign that port name to serial port.
Code is as follows Dim SP as string

Private Sub frmSelectPort_Load(sender as Object,  e as 
System. EventArgs)  Handles Me. Load 
GetSerialPortnames 
End Sub

 Sub GetSerialPortnames () For Each SP In My. Computer. 
   SerialPortNames
   Listbox1. Items. Add(sp) 
 End Sub


 (Under button click event) 
SP =Listbox1. SelectedItem
SerialPort1. PortName=SP 
SerialPort1. Open()