SerialPort在传输时丢失数据--抱歉每分给大家散,请帮忙指点迷津
最近工作之余,在学习一些串口得知识,或许是基础太差了,总是碰到一些问题,解决不了。 请教大家一下。
在串口传送一些大得数组,总是会丢失一些数据,例如我发送一个02 01 00 00 00 00 00 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 23,当程序刚运行时,
第一次在接收端可以接收得数据02 01 00 00 00 00 00 00 00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 23
第二次再发送同样得数组接收得就是02 01 00 00 00 00 00 00
第三次,第四次..再发送同样得数组接收得是00 00 00 20 00 00 00 00 00 00 00 00 00 00 00 00 00 23 02 01 00 00 00 00 00 00
SerialPort1.ReceivedBytesThreshold 我也有设置过,但是还是总是丢失。
当发送一个02 01 02 00 00 00 00 00 01这样得数组就不会丢失数据。
发送端代码:
程序代码:
Sub sendmessage() Dim i As Integer 'Me.SerialPort1.DiscardInBuffer() If CheckBox2.Checked = True Then strHex = sendtxt.Text ReDim byteSEnd(Len(strHex) \ 3) For i = 1 To Len(strHex) Step 3 byteSEnd((i - 2) / 3) = Val("&H" & Mid(strHex, i, 3)) Next Me.SerialPort1.Write(byteSEnd, 0, byteSEnd.Length) readmessage() Else Me.SerialPort1.Write(sendtxt.Text) readmessage() End If If CheckBox1.Checked = True Then Timer1.Enabled = True Timer1.Interval = TextBox1.Text End If End Sub
接收端代码:
程序代码:
Sub readmessage() If CheckBox2.Checked = True Then Dim j As Integer Dim temp As String Dim mSize As Integer = Me.SerialPort1.BytesToRead ReDim receiveData(mSize - 1) Me.SerialPort1.Read(receiveData, 0, mSize) Me.SerialPort1.ReceivedBytesThreshold = 1000 If mSize > 0 Then For j = 0 To UBound(receiveData) ' 根据接收到的16进制数据长度,逐个字节显示 temp = Hex(receiveData(j)) If Len(temp) = 1 Then temp = "0" & Hex(receiveData(j)) Else temp = Hex(receiveData(j)) End If Receivedtxt.Text = Me.Receivedtxt.Text + temp + " " Next j End If Else Receivedtxt.AppendText(Me.SerialPort1.ReadExisting) 'System.Threading.Thread.Sleep(1000) Me.Receivedtxt.ScrollToCaret() End If Me.messagelab2.Text = "信息已传输完毕" End Sub
请大家支招,怎样避免在传送大数组时丢失数据,谢谢~~