-
Open 2 comports
Hi
I have an app that is talking to a device via the serial port. Now if I want to talk to an other device at same time with an other serial port, which would be the best way of doing this? I'll provide my code to talk to one device.
On form load I check all ports:
Code:
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
For i As Integer = 0 To _
My.Computer.Ports.SerialPortNames.Count - 1
cbbCOMPorts.Items.Add( _
My.Computer.Ports.SerialPortNames(i))
Next
End Sub
Then I open the port:
Code:
Private Sub btnConnect_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnConnect.Click
If serialPort.IsOpen Then
serialPort.Close()
End If
Try
With serialPort
.PortName = cbbCOMPorts.Text
.BaudRate = cbbBaud.Text
.Parity = paritet
.DataBits = cbbData.Text
.StopBits = cbbStopbits.Text
End With
serialPort.Open()
With txtDataReceived
.AppendText(vbCrLf & "< Trying to open " & cbbCOMPorts.Text & vbCrLf)
.AppendText("> " & cbbCOMPorts.Text & " is open")
.SelectionStart = Len(txtDataReceived.Text)
.ScrollToCaret()
.Select()
End With
Catch ex As Exception
MsgBox("Select a ComPort")
End Try
End Sub
Handle the datareceived:
Code:
Public Delegate Sub myDelegate()
Private Sub updateTextBox()
With txtDataReceived
.AppendText(serialPort.ReadExisting)
.SelectionStart = Len(txtDataReceived.Text)
.ScrollToCaret()
.Select()
End With
End Sub
Private Sub DataReceived( _
ByVal sender As Object, _
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) _
Handles serialPort.DataReceived
txtDataReceived.Invoke(New _
myDelegate(AddressOf updateTextBox), _
New Object() {})
If chkLog.Checked Then
IO.File.WriteAllText(Me.fileName, txtDataReceived.Text)
End If
End Sub
Sending and receiving a command:
Code:
Private Sub btnAutoOn_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnSetCC.Click
Try
serialPort.Write("AutoOn" & vbCr)
With txtDataReceived
.AppendText(vbCrLf & "< AutoMode is On" & vbCrLf)
.AppendText("> ")
.SelectionStart = Len(txtDataReceived.Text)
.ScrollToCaret()
.Select()
End With
Catch ex As Exception
MsgBox("YOU Must Open Com Port")
End Try
End Sub