【急用】怎么样通过VB向串口发送和接收十六进制指令?
买了个通过串口接受和发送指令的温度、气压传感器,已经通过串口测试软件测试过,只能发送十六进制指令,形如14 04 00 02 00 01 92 CF。现在想通过VB利用MSCOMM组件编程实现控制,但不知道如何做。大伙帮个忙,谢谢大家来!
[解决办法]
定义一个byte类型的数组放入你要发送的16进制的数据,长度根据需要定
dim a(10) as byte
a(0)=&H16
a(1)=&H04
....
MSCOMM初始化一下
mscDemo.CommPort = 1 mscDemo.Settings = "9600,n,8,1" mscDemo.InputMode = comInputModeBinary mscDemo.PortOpen = True
[解决办法]
Option Explicit Dim strData As StringPrivate Sub Form_Load() MSComm1.Settings = "9600,N,8,1" MSComm1.RThreshold = 1 MSComm1.InputMode = comInputModeBinary MSComm1.PortOpen = True End Sub Private Sub Command1_Click() '发送2进制字节数据流 Dim sj(7) As Byte '14 04 00 02 00 01 92 CF sj(0) = &H14 sj(1) = &H4 sj(2) = &H0 sj(3) = &H2 sj(4) = &H0 sj(5) = &H1 sj(6) = &H92 sj(7) = &HCF MSComm1.Output = sj End SubPrivate Sub MSComm1_OnComm() '接收数据 Dim strBuff As String Select Case MSComm1.CommEvent Case 2 MSComm1.InputLen = 0 strBuff = MSComm1.Input BytReceived() = strBuff jieshou '数据处理代码 End Select End Sub Public Function jieshou() '接收数据处理为16进制 Dim i As Integer For i = 0 To UBound(BytReceived) If Len(Hex(BytReceived(i))) = 1 Then strData = strData & "0" & Hex(BytReceived(i)) Else strData = strData & Hex(BytReceived(i)) End If Next End Function