LZ的代码错在:
Dim send(4) As Byte
它定义的Byte数组有5个元素,所以单片机不返回数据。应该改为:
Private Sub Command1_Click() '发送HEX数据93 93 93 93
Dim send(3) As Byte
send(0) = "&H93"
send(1) = "&H93"
send(2) = "&H93"
send(3) = "&H93"
MSComm1.Output = send
End Sub
这样才发送4字节指令,此外从MSComm1.RThreshold = 34看是设置接收字节长度为34字节。
以下修改了LZde1代码,供参考:
Option Explicit
Dim strdata
Private Sub Command1_Click() '发送HEX数据93 93 93 93
Dim send(3) As Byte
send(0) = "&H93"
send(1) = "&H93"
send(2) = "&H93"
send(3) = "&H93"
MSComm1.Output = send
End Sub
Private Sub Form_Load()
'串口初始化
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputLen = 0
MSComm1.InputMode = comInputModeBinary
MSComm1.InBufferSize = 1024
MSComm1.OutBufferSize = 512
MSComm1.RThreshold = 34 '设置接收字节长度
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.CommPort = 1 '串口号
MSComm1.PortOpen = True
Timer1.Interval = 0
End Sub
Private Sub MSComm1_OnComm()
Dim i As Long
Dim strBuff As String
Dim strdata As String
Dim str() As Byte
Select Case MSComm1.CommEvent
Case comEvReceive
strBuff = MSComm1.Input
str() = strBuff
For i = 0 To UBound(str) '接收16进制数据
If Len(Hex(str(i))) = 1 Then
strdata = strdata & "0" & Hex(str(i))
Else
strdata = strdata & Hex(str(i))
End If
Next
Text1.Text = strdata
Call Timer1_Timer
End Select
End Sub
Private Sub Timer1_Timer()
strdata = ""
MSComm1.InBufferCount = 0
End Sub
修改这里。。。
Private Sub MSComm1_OnComm()
Dim strBuff As String
Dim strdata As String
Dim str() As Byte
Select Case MSComm1.CommEvent
Case comEvReceive
strBuff = MSComm1.Input
str() = strBuf
在这里添加接收字符长度的判断,长度够了再接收。处理。。
For i = 0 To UBound(str) '接收16进制数据
If Len(Hex(str(i))) = 1 Then
strdata = strdata & "0" & Hex(str(i))
Else
strdata = strdata & Hex(str(i))
End If
Next
你简单的个通讯给你写的这么复杂。
你直接发送output
然后等待50ms最少
直接input就OK了。