VB中使用mscomm时的延时问题
发布网友
发布时间:2024-10-18 09:51
我来回答
共2个回答
热心网友
时间:2024-10-23 14:12
你可直接使用MSComm控件的OnComm事件接收,若按9600BIT,基本每秒能接收960字节数据,即使250毫秒中也能收取240个字节数据:
Option Explicit
Dim BytReceived() As Byte
Dim strData As String
Dim lenInput As Integer
Private Sub Form_Load()
MSComm1.CommPort = 1 'COM端口
MSComm1.Settings = "9600,n,8,1"
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 140 '产生MSComm事件
MSComm1.InBufferSize = 1024
MSComm1.PortOpen = True
Text1 = ""
Text3 = ""
LblJieshou = ""
Text4 = ""
Timer1.Interval = 0
End Sub
Private Sub MSComm1_OnComm()
On Error Resume Next
Dim strBuff As String
Text1 = ""
Select Case MSComm1.CommEvent
Case 2
MSComm1.InputLen = 0
strBuff = MSComm1.Input
BytReceived() = strBuff
jieshou
LblJieshou = Text1
lenInput = Len(LblJieshou)
Text3 = lenInput \ 2
Text2 = Mid(LblJieshou, 1, 2)
End Select
Timer1_Timer
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
Text1 = strData
End Function
Private Sub Timer1_Timer()
strData = ""
End Sub
补充:
就是按2400BIT,每秒接收240字节应该无问题。
热心网友
时间:2024-10-23 14:12
用mscomm的事件
dim recstr as string
Private Sub MSComm1_OnComm()
Dim S() As Byte
S = MSComm1.Input '只要有数据就收进来,哪怕只是一个
For i = 0 To UBound(S) '一个数据包可能产生若干个oncomm事件
recstr = recstr + Right("0" + Hex(Int(Str(S(i)))), 2)
next
end sub