gpt4 book ai didi

VB.NET 将 USB 转换为 RS232

转载 作者:行者123 更新时间:2023-12-04 04:30:20 24 4
gpt4 key购买 nike

我有一个带 USB 的硬件,用于计算机与硬件之间的通信。供应商不提供任何 API 来连接到设备。他们给了我一个协议(protocol)。但该协议(protocol)适用于 RS232 模式。我问供应商这个协议(protocol)是否可以应用于 USB,他们说"is"。所以,我很想知道如何使用这个协议(protocol)。有人知道吗?我的老 friend 说是的,我可以使用 USB 并将其视为 COM,我需要创建一个对象。创建声明为串行端口的对象的实例,如下所示。但是还是获取不到状态。

Public Sub New(ByVal intComNumber As Integer, ByVal lngBaudRate As Long, ByVal intDataLng As Integer, ByVal intStopBit As Integer, ByVal intParity As Integer)
Try
objUPSPort = New SerialPort
With objUPSPort
.PortName = ("COM" & intComNumber)
.BaudRate = lngBaudRate
.DataBits = intDataLng
.StopBits = intStopBit
.Parity = intParity
.Handshake = Handshake.None
End With
Catch ex As Exception
MsgBox("Error In Init UPSComm")
End Try
End Sub

有人可以帮我识别吗?这个硬件就是 UPS。一个简单的命令写入端口。但是在获取状态时出现错误。下面是写入 UPS 的代码。

Public Function GetStatus() As String
Dim strRet As String
Dim strRecv As String
Dim byteRead() As Byte
Try
If Not IsNothing(objUPSPort) Then
objUPSPort.Open()
objUPSPort.WriteLine("Command will be here" & vbCrLf)

For i = 0 To 100000
If objUPSPort.BytesToRead >= 45 Then
Exit For
End If
Next
ReDim byteRead(objUPSPort.BytesToRead)
objUPSPort.Read(byteRead, 0, objUPSPort.BytesToRead)
strRecv = String.Empty
For i = 0 To byteRead.Length - 1
strRecv = strRecv & Chr(byteRead(i))
Next
If byteRead(38) = 48 Then
MsgBox("Power OK")
ElseIf byteRead(38) = 49 Then
MsgBox("Power Off")
Else
MsgBox("Unknown")
End If
strRet = strRecv
Return strRecv
Else
MsgBox("Error In ComPort Object")
Return String.Empty
End If
Catch ex As Exception
MsgBox("Exception In ComPort Object - " & ex.Message)
Return String.Empty
Finally
objUPSPort.Close()
End Try
End Function

最佳答案


我几乎没有使用 USB 进行 RS232 通信的经验,因为现在笔记本电脑/个人电脑不再配备串行端口。串行端口通常由 USB 模拟,使用 [TTL-to-RS232 晶体管,MAX 类] 一些常见的供应商会使用 prolific 作为驱动程序来模拟 USB-to-RS232。首先,您需要知道数据类型,简单的字符串或二进制。

SerialPorts 是事件驱动的,通过端口的数据可以触发事件。我假设要让 UPS 向您发送状态信息,首先,您需要发送命令,例如 [some pseudo];

objUPSPort.WriteLine("Command will be here" & vbCrLf)

获取数据的方式有两种:

  • 使用数据接收事件驱动:
Private Sub objUPSPort_DataReceived(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles objUPSPort.DataReceived
'call ReceiveData()
End Sub
  • 创建一个池化线程定期读取数据
Private Sub threadUPSReceive() 
Do
data = objUPSPort.ReadLine() 'for string
'process the data here or call ReceiveData()
Loop
End Sub

如果要读取的数据流是二进制的(类似于你的):

Private Function ReceiveData()

Dim bRead As Integer
Dim returnStr As String = vbEmpty
bRead = objUPSPort.BytesToRead 'Number of Bytes to read
Dim cData(bRead - 1) As Byte

For Each b As Byte In cData
returnStr += Chr(b) 'put data stream in readable ascii
Next

Return returnStr
End Sub

还有一件事,确保波特率/停止位/数据位设置正确。希望对您有所帮助。

关于VB.NET 将 USB 转换为 RS232,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22682654/

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