我有一个带USB的硬件,用于计算机与硬件之间的通信。供应商未提供任何API以连接到设备。他们给了我一个协议。但该协议适用于RS232模式。我问供应商这个协议是否可以应用于USB,他们说“是”。所以,我想知道如何使用这个协议。有人知道吗?我的老朋友说是的,我可以使用USB并将其视为创建对象所需的COM。创建声明为serialport的对象的实例,如下所示。但它仍然无法获得该状态。
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
答案 0 :(得分:1)
我在使用USB的RS232通信方面几乎没有经验,因为现在的笔记本电脑/电脑不再带有串口。串口通常由USB模拟,使用[TTL-to-RS232晶体管,MAX类似]一些常见的供应商将使用多产的驱动程序来模拟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
还有一件事,请确保正确设置波特率/停止位/数据位。 希望这有帮助。