vb 如何使用mscomm1部件串口通信接收发送十六进制数据代码

工控评论

vb 如何使用mscomm1部件串口通信接收发送十六进制数据代码,网友分享的代码,没有实际验证,不过读了一下程序,似乎没有问题。

Private Sub Command1_Click()
Dim OutBuffer() As Byte
Dim tem As Variant
Dim e As Integer
Dim q As Integer
Dim LenOfText As Integer
LenOfText = Len(txtSum.Text) / 2 - 1
ReDim OutBuffer(LenOfText)
If MSComm1.PortOpen = False Then
MSComm1.PortOpen = True
End If
q = 0
For e = 1 To Len(txtSum.Text) Step 2
tem = Mid(txtSum.Text, e, 2)
OutBuffer(q) = Val("&H" & tem)
Debug.Print Val("&H" & tem)
q = q + 1
Next
MSComm1.Output = OutBuffer
End Sub

Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.Settings = "19200,N,8,1"
MSComm1.InputMode = comInputModeBinary
MSComm1.InputLen = 0
MSComm1.InBufferSize = 1024
MSComm1.OutBufferSize = 512
MSComm1.PortOpen = True
MSComm1.SThreshold = 0
MSComm1.RThreshold = 1
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
End Sub

Private Sub MSComm1_OnComm()
On Error Resume Next
Dim BytesReceived() As Byte
Dim buffer As String
Dim HData As String
Dim i As Integer
Select Case MSComm1.CommEvent
Case comEvReceive '接收十六进制数据。并以十六进制显示
MSComm1.InputLen = 0
buffer = MSComm1.Input '接收数据至字符串中
BytesReceived() = buffer '将数据转入Byte数组中
For i = 0 To UBound(BytesReceived) '显示结果以十六进制显示
If Len(Hex(BytesReceived(i))) = 1 Then
HData = HData & "0" & Hex(BytesReceived(i))
Else
HData = HData & Hex(BytesReceived(i))
End If
Text1.Text = HData
'最后将结果后入Text1中
MSComm1.OutBufferCount = 0 '清除发送缓冲区
MSComm1.InBufferCount = 0 '清除接收缓冲区
MSComm1.PortOpen = False
Next
End Select
End Sub

 

运营不易,
感谢支持!
weinxin
我的微信
我的微信公众号
我的微信公众号扫一扫
weinxin
我的公众号
 
公式库网
  • 本文由 公式库网 发表于 2020年5月31日20:17:39
  • 转载请务必保留本文链接:https://www.gongshiku.com/html/202005/vb-ruheshiyongmscomm1bujianchuankoutongxinjieshoufasongshiliujinzhishujudaima.html
  • vb串口通信

发表评论