读书人

串口通讯延时的有关问题

发布时间: 2012-02-23 22:01:35 作者: rapoo

串口通讯延时的问题
Private Sub Command1_Click()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,2 "
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.InputLen = 0
MSComm1.PortOpen = True
Dim arri(7) As Byte
arri(0) = &H11
arri(1) = &H30
arri(2) = &H30
arri(3) = &H31
arri(4) = &H30
arri(5) = &H31
arri(6) = &H3
MSComm1.Output = arri
For inttemp1 = 0 To 10000000
Next
Text1.Text = MSComm1.Input
End Sub
这段代码是从串口读取数据
其中
For inttemp1 = 0 To 10000000
Next
是为了延时,否则读不出返回的数据
这个延时除了用循环或timer控件,还有别的更好的方法嘛,因为这段代码读取的是一块表中一个通道的数据,我总共要读取20块表,共460个通道的数据,采集周期是3分钟,如果用这个循环的方法延时太耗资源了,有更好的方法嘛

[解决办法]
使用API函数,可在毫秒级水平上延迟:
Option Explicit
Private Declare Sub Sleep Lib "kernel32 " (ByVal dwMilliseconds As Long)
Private Sub Command1_Click()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,2 "
MSComm1.InBufferCount = 0
MSComm1.OutBufferCount = 0
MSComm1.InputLen = 0
MSComm1.PortOpen = True
Dim arri(7) As Byte
arri(0) = &H11
arri(1) = &H30
arri(2) = &H30
arri(3) = &H31
arri(4) = &H30
arri(5) = &H31
arri(6) = &H3
MSComm1.Output = arri
Sleep(100) '延迟100毫秒
Text1.Text = MSComm1.Input
End Sub

[解决办法]
那你直接将接收代码放MSCOMM的ONCOMM事件中:
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 Form_Load()
MSComm1.CommPort = 1 'COM端口
MSComm1.Settings = "9600,n,8,1 "
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 1 '产生MSComm事件
MSComm1.InBufferSize = 1024
MSComm1.PortOpen = True
Text1 = " "
Text3 = " "
LblJieshou = " "
Text4 = " "
Timer1.Interval = 0
End Sub

------解决方案--------------------


修正:
Private Sub Form_Load()
MSComm1.CommPort = 1 'COM端口
MSComm1.Settings = "9600,n,8,2 "
MSComm1.InputMode = comInputModeBinary '采用二进制传输
MSComm1.InBufferCount = 0 '清空接受缓冲区
MSComm1.OutBufferCount = 0 '清空传输缓冲区
MSComm1.RThreshold = 1 '产生MSComm事件
MSComm1.InBufferSize = 1024
MSComm1.PortOpen = True
Text1 = " "
Text3 = " "
LblJieshou = " "
Text4 = " "
End Sub

读书人网 >VB

热点推荐