listbox 无法显示正常接收到的数据。
[code=VB][/code]Dim data, data1 As Variant '串口初始化
Private Sub Command2_Click()
List1.Clear 'list1清空
End Sub
Private Sub Form_Load()
MSComm1.CommPort = 1 ' 设置通信端口号为COM1
MSComm1.Settings = "9600,n,8,1" ' 设置串口1参数
MSComm1.InputMode = comInputModeBinary ' 接收二进制数据
MSComm1.InputLen = 0 '读取缓冲区全部数据
MSComm1.RThreshold = 1 '当缓冲区数据到达1时产生oncomm事件
If MSComm1.PortOpen = True Then MSComm1.PortOpen = False
If MSComm1.PortOpen = False Then MSComm1.PortOpen = True ' 打开通信端口1
End Sub
Private Sub Command1_Click()
MSComm1.OutBufferCount = 0 '清除发送缓冲区
MSComm1.Output = "#018" + vbCr
End Sub
Private Sub mscomm1_OnComm()
Dim Recive As String
If MSComm1.CommEvent = 2 Then
Recive = MSComm1.Input
For i = 1 To Len(Recive)
List1.AddItem Right("00" & Hex(Asc(Mid(Recive, i, 1))), 2) & " "
Next i
End If
End Sub
接收到的数据是3F31623F......
而监测到的数据是3E303100......
[解决办法]
- VB code
Option ExplicitDim data, data1 As Variant '串口初始化Private Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)Private Sub Command2_Click() List1.Clear 'list1清空End SubPrivate Sub Form_Load() MSComm1.CommPort = 1 ' 设置通信端口号为COM1 MSComm1.Settings = "9600,n,8,1" ' 设置串口1参数 MSComm1.InputMode = comInputModeBinary '接收二进制数据 MSComm1.InputLen = 1 '每个Input只读取缓冲区中一个数据 MSComm1.RThreshold = 1 '当缓冲区数据到达1时产生oncomm事件 If MSComm1.PortOpen = True Then MSComm1.PortOpen = False If MSComm1.PortOpen = False Then MSComm1.PortOpen = True ' 打开通信端口1End SubPrivate Sub Command1_Click() MSComm1.OutBufferCount = 0 '清除发送缓冲区 MSComm1.Output = "#018" + vbCr Sleep 20 '发送命令后等待20ms,以便等待下位机数据返回(根据实际情况,可以取消)End SubPrivate Sub mscomm1_OnComm() Dim Recive As Variant Dim strP As String If MSComm1.CommEvent = 2 Then Sleep 20 '继续等待20ms,以便等待下位机数据返回(根据实际情况,可以取消) MSComm1.RThreshold = 0 '设置此值为0,避免后续接收到的数据继续触发不必要的OnComm事件 Do Recive = MSComm1.Input If Not IsNull(Recive) Then strP = Right("00" & Hex(Recive(0)), 2) List1.AddItem strP End If Loop Until MSComm1.InBufferCount = 0 End IfEnd Sub