VB串口搜索正在发送数据的串口,并将数据按包大小对齐
[复制链接]
串口转usb模块后插到电脑上以后串口号不固定,每次都要查看设备再改参数比较麻烦,下面这段可以完成正在发送数据的串口的搜索,搜索到串口并正常收到数据后检查特定的数据标识是否正确,如果不正确认为串口收包没有对齐再等几个数据直到标识正确.
VB的程序片段仅供参考.
'数据接收
Public Function Com_Recived() As Boolean
'条件检查
strBuff = MainForm.MSComm1.Input
'复制数据
ReciveDataSize = UBound(strBuff)
If (ReciveDataSize > 39) Then ReciveDataSize = 39
For i = 0 To ReciveDataSize
Com_Recive_Data(i) = strBuff(i)
Next
If ReciveDataSize = (COMDATASIZE - 1) Then
If Com_Recive_Data(0) = COMPACK_H1 And Com_Recive_Data(1) = COMPACK_H2 Then
MainForm.MSComm1.RThreshold = COMDATASIZE
Com_Recived = True
'掉线检测
TestDelay = 0
MainForm.Shape2.FillColor = RGB(0, 255, 0)
Com_Port = Com_Port_Test
Else
'数据标志检测错误
MainForm.Shape2.FillColor = RGB(255, 255, 0) '黄
MainForm.MSComm1.RThreshold = 3
Com_Recived = False
End If
Else
'数据不对齐
ret = Com_DebugList(ReciveDataSize, 0)
If Com_Recive_Data(0) = COMPACK_H1 And Com_Recive_Data(1) = COMPACK_H2 Then
'清空调试
MainForm.DebugLable.Caption = ""
Com_Recived = False
MainForm.MSComm1.RThreshold = COMDATASIZE
Com_Port = Com_Port_Test
MainForm.MSComm1.PortOpen = False
MainForm.MSComm1.PortOpen = True
Else
MainForm.Shape2.FillColor = RGB(255, 255, 0) '黄
MainForm.MSComm1.RThreshold = 3
End If
End If
End Function
Public Function ComPort_Init() As Boolean
If MainForm.MSComm1.PortOpen = True Then '端口已经打开
'延时时间内未收到数据切换端口
TestDelay = TestDelay + 1
MainForm.DebugLable.Caption = MainForm.DebugLable.Caption & Str(TestDelay)
If TestDelay > 9 Then
TestDelay = 0
MainForm.MSComm1.PortOpen = False
End If
Else '端口未打开,从1~16中找一个可以打开的
If Com_Port_Test > 16 Then Com_Port_Test = 1
On Error Resume Next '当运行发生错误时,控件转到紧接着发生错误的语句之后的语句,并在此继续运行
MainForm.MSComm1.CommPort = Com_Port_Test
MainForm.MSComm1.PortOpen = True
Select Case Err.Number
Case 0 '错误号为0(也就是没出错),
MainForm.DebugLable.Caption = "等待端口" & Str(Com_Port_Test) & "数据"
Case 8002 '端口不存在
MainForm.DebugLable.Caption = "端口" & Str(Com_Port_Test) & "不存在"
MainForm.MSComm1.PortOpen = False
Case 8005 '错误号为8005,也就是端口被占用
MainForm.DebugLable.Caption = "端口" & Str(Com_Port_Test) & "已经占用"
MainForm.MSComm1.PortOpen = False
End Select
Com_Port_Test = Com_Port_Test + 1
Err = 0 '将错误号置0. 注:Err.Number可以简写为Err ,2者等效
End If
End Function
[ 本帖最后由 huo_hu 于 2013-4-8 15:55 编辑 ]
|