读书人

大家帮忙看看,串口通讯有关问题.接收数

发布时间: 2012-02-10 21:27:42 作者: rapoo

大家帮忙看看,串口通讯问题.接收数据时好时坏,谢谢了!
一只仪表与上位机通讯,采用MODBUS协议,用 "串口调试助手 "接受数据正常,共69位,用以下程序接受,部份数据接受有时正确有时不正确,请大家告诉我究竟错哪?


Dim a(100) As String
Dim b(100) As String
Dim c(100) As Single
Dim flag As Boolean

Private Sub Command1_Click()

Dim SendStr(8) As Byte
Dim RcvStr() As Byte
Dim inx() As Byte
Dim bl As Integer
Dim eddl As Single


MSComm1.InputMode = comInputModeBinary
MSComm1.InBufferCount = 0
If Not MSComm1.PortOpen Then MSComm1.PortOpen = True
If Command1.Caption = "开始测试 " Then
Command1.Caption = "停止测试 "
Label1(31).Caption = 1
flag = True
Else
Command1.Caption = "开始测试 "
flag = False
End If


SendStr(0) = &H1 '从站号是1
SendStr(1) = &H3 '读多个字的命令代码
SendStr(2) = &H8 '起始地址高字节
SendStr(3) = &H0 '起始地址低字节
SendStr(4) = &H0 '数据长度高字节
SendStr(5) = &H20 '数据长度低字节
SendStr(6) = &H46
SendStr(7) = &H72


Do While flag

For i = 0 To 68
a(i) = " "
Next

t1 = Timer
Do
t2 = Timer
If Abs(t2 - t1) > = 0.3 Then Exit Do


DoEvents
Loop


If Not MSComm1.PortOpen Then MSComm1.PortOpen = True
MSComm1.Output = SendStr '发送命令

MSComm1.RThreshold = 69

If Abs(Val(Label1(31).Caption) - 400) <= 0.2 Then
Command1.Caption = "开始测试 "
flag = False
End If



以下省略....


End Sub


Private Sub Form_Load()

MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,1 "
'MSComm1.SThreshold = 69
MSComm1.InBufferSize = 1024
MSComm1.InputLen = 0
MSComm1.RThreshold = 69
MSComm1.InputMode = comInputModeBinary
If Not MSComm1.PortOpen Then MSComm1.PortOpen = True
End Sub


Private Sub MSComm1_OnComm()
Select Case MSComm1.CommEvent
Case comEvReceive '判断为接收事件
MSComm1.InputLen = 69 '接收数据的长度

inx = Null
If Not MSComm1.PortOpen Then MSComm1.PortOpen = True
inx = MSComm1.Input '接收数据

For i = LBound(inx, 1) To UBound(inx, 1)
a(i) = Hex(inx(i))
Next

MSComm1.InBufferCount = 0 '********************** '清空缓冲
If MSComm1.PortOpen Then MSComm1.PortOpen = False



End Select
End Sub


[解决办法]
Option Explicit
Dim a() As Byte
Dim strdata
Private Sub Form_Load()
MSComm1.CommPort = 1
MSComm1.Settings = "9600,n,8,1 "
MSComm1.SThreshold = 69
MSComm1.InBufferSize = 1024
MSComm1.InputLen = 0
MSComm1.RThreshold = 69
MSComm1.InputMode = comInputModeBinary
If Not MSComm1.PortOpen Then MSComm1.PortOpen = True
End Sub

Private Sub MSComm1_OnComm()
Dim inbuff As String
Select Case MSComm1.CommEvent
Case comEvReceive '判断为接收事件
inbuff = MSComm1.Input '接收数据的长度
a = inbuff
jieshou
strdata = " "
End Select
End Sub
Public Function jieshou() '接收数据处理为16进制
Dim i As Integer
For i = 0 To UBound(a)
If Len(Hex(a(i))) = 1 Then
strdata = strdata & "0 " & Hex(a(i))
Else
strdata = strdata & Hex(a(i))
End If
Next
Text1 = strdata
End Function

读书人网 >VB

热点推荐