gpt4 book ai didi

vb.net - 打开多个 COM 端口并发送/接收数据

转载 作者:行者123 更新时间:2023-12-02 05:36:48 26 4
gpt4 key购买 nike

我正在尝试设置一个程序,允许您打开多个 COM 端口,然后选择要发送数据的 COM 端口。我使用的计算机有 18 个 COM 端口。另外,在第一个代码中,它显示端口已打开,他们只是不会接收任何内容。

Dim Ports As New List(Of IO.Ports.SerialPort)

Ports.Add(New IO.Ports.SerialPort)

Ports(0).PortName = "COM1"
Ports(0).BaudRate = 9600
Ports(0).DataBits = 8
Ports(0).StopBits = IO.Ports.StopBits.One
Ports(0).Open()


'Data Received Interrupt to read and display anything coming in the RXD pin.
Private Sub SerialPort1_Datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
CheckForIllegalCrossThreadCalls = False
Dim data As String

'rxListBox.Items.Add(data)
data = Ports(0).ReadExisting.ToString()

End Sub

这就是我正在尝试做的,但我无法让它接收数据。如果我将代码更改为下面列出的代码,它可以工作,但我想要一种在带有数组的端口之间切换的方法。

'Setup serial Port parameters
SerialPort1.PortName = "COM1"
SerialPort1.BaudRate = 9600
SerialPort1.DataBits = 8
SerialPort1.StopBits = IO.Ports.StopBits.One
SerialPort1.Open()

'Data Received Interrupt to read and display anything coming in the RXD pin.
Private Sub SerialPort1_Datareceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
CheckForIllegalCrossThreadCalls = False
Dim data As String

data = SerialPort1.ReadExisting.ToString()
rxListBox.Items.Add(data)
End Sub

谢谢

最佳答案

您必须将处理程序添加到您创建的每个端口

For each port in Ports
AddHandler port.DataReceived, AddressOf SerialPort1_Datareceived
Next

创建所有端口后运行该命令。您还必须在 SerialPort1_Datareceived 事件中检查来自哪个端口数据。

关于vb.net - 打开多个 COM 端口并发送/接收数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6283163/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com