Author: Imtiyaz Momin.
Purpose is to share the knowledge and take the project to next level.
STEP 1:
Add Combobox cboBaud
Add Button btnScan
Add Label lblMessage
STEP 2:
Imports System.IO.Ports
Imports System.IO
Imports System.Threading
Public Class GPS
Private port As SerialPort = New SerialPort
Private ScanPort As Thread
Public Delegate Sub printMessageInvoker(ByVal objCtr As Control, ByVal messageToPrint As String)
Public Delegate Function getBaudRateInvoker() As String
Public Delegate Sub setCommPortInvoker(ByVal strCom As String)
Private Sub GPS_Load(ByVal sender As Object, ByVal e As System.EventArgs)
Dim ports() As String = SerialPort.GetPortNames
For Each strCom As String In ports
cboPorts.Items.Add(strCom)
Next
cboBaud.Items.Add("4800")
cboBaud.Items.Add("9600")
cboBaud.Items.Add("38400")
cboBaud.SelectedIndex = 0
End Sub
Private Sub btnScan_Click(ByVal sender As Object, ByVal e As System.EventArgs)
If (btnScan.Text = "Stop") Then
btnScan.Text = "Scan"
ScanPort.Abort
Return
End If
ScanPort = New Thread(AddressOf Me.ScanGPSPort)
ScanPort.Start
btnScan.Text = "Stop"
End Sub
Private Sub ScanGPSPort()
Dim ports() As String = SerialPort.GetPortNames
Dim i As Integer = ports.Length
Dim j As Integer = 0
Dim strMsg As String = ""
lblMessage.Invoke(New printMessageInvoker(AddressOf Me.PrintMessage), New Object() {lblMessage, "Scanning..."})
For Each strCom As String In ports
If port.IsOpen Then
port.Close
End If
Try
lblMessage.Invoke(New printMessageInvoker(AddressOf Me.PrintMessage), New Object() {lblMessage, ("Scanning port " + strCom)})
cboPorts.Invoke(New setCommPortInvoker(AddressOf Me.setCommPort), New Object() {strCom})
Application.DoEvents
port.PortName = strCom
port.Parity = Parity.None
port.BaudRate = Invoke(New getBaudRateInvoker(AddressOf Me.getBaudRate)).ToString
port.StopBits = StopBits.One
port.DataBits = 8
port.Open
Thread.Sleep(2000)
strMsg = port.ReadLine
If strMsg.StartsWith("$G") Then
lblMessage.Invoke(New printMessageInvoker(AddressOf Me.PrintMessage), New Object() {lblMessage, ("Connected to port " + strCom)})
btnScan.Invoke(New printMessageInvoker(AddressOf Me.PrintMessage), New Object() {btnScan, "Scan"})
Try
ScanPort.Abort
Catch ex As Exception
Exit For
Return
End Try
End If
Catch ex As Exception
End Try
Next
ScanGPSPort()
End Sub
Private Sub setCommPort(ByVal strCom As String)
cboPorts.SelectedItem = strCom
End Sub
Private Function getBaudRate() As String
Return cboBaud.SelectedItem
End Function
Private Sub PrintMessage(ByVal objCtr As Control, ByVal messageToPrint As String)
objCtr.Text = messageToPrint
End Sub
End Class
|