出现干扰 如何接收串口数据
本帖最后由 use_zj 于 2010-04-22 14:57:03 编辑 AA 01 12 43 B4 85 06 1F BC 90 33 FF 一组正常数据
AA 01 12 D3 14 80 A6 1F BC 90 FF
AA 0A D2 43 B4 45 56 1F BC 90 FF
AA 02 12 43 B4 85 06 1F BC 90 33 FF 一组正常数据
AA 01 12 D3 14 80 A6 45 56 45 56 1F BC 90 FF
AA 0A D2 43 B4 45 56 1F BC 90 FF
AA 03 12 43 B4 85 06 1F BC 90 33 FF 一组正常数据
AA 01 12 D3 14 80 A6 1F BC 90 FF
AA 0A D2 43 B4 45 56 45 56 45 56 1F BC 90 FF
下位机发这样的数据,间隔10ms,12个字节的数据是正常数据,其他的都是受干扰后的数据,我不知道用什么方法能拿到正确的数据??????下面是我的代码,但是收不全,会少数据
Public Class Form1
'定义一个数据缓冲池,这里用Collection对象作缓冲池,你也可以用数组或其他东西
Dim coldata As Collection
Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
'初始化数据缓冲池
coldata = New Collection
'初始化并打开串口
AxMSComm1.CommPort = 1
AxMSComm1.InBufferSize = 1024
AxMSComm1.OutBufferSize = 1024
AxMSComm1.Settings = "19200,N,8,1"
AxMSComm1.RThreshold = 1 '设置为每收到一个字节数据触发一次Oncomm事件
AxMSComm1.InputMode = MSCommLib.InputModeConstants.comInputModeBinary
AxMSComm1.PortOpen = True
End Sub
Private Sub AxMSComm1_OnComm(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles AxMSComm1.OnComm
Dim yy As Integer
Select Case AxMSComm1.CommEvent
Case MSCommLib.OnCommConstants.comEvReceive
Dim xx() As Byte
xx = AxMSComm1.Input
For yy = 0 To UBound(xx) '把串口接收到的所有数据都先保存到数据缓冲池暂时不去处理,因为无法保证数据已经接收完整
coldata.Add(xx(yy))
Next yy
End Select
Timer1.Start() ‘interval 10ms
End Sub
'用Timer控件循环对接收到的数据进行处理
Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
If coldata.Count <> 12 Then
coldata.Clear()
'Exit Sub '收到的数据不足12个
Timer1.Stop()
Else
Dim xx As Integer
If coldata.Item(1) <> &HAA Or coldata.Item(12) <> &HFF Then
coldata.Clear() '丢弃
Timer1.Stop()
Else
For xx = 1 To 12 '遍历所有串口收到的数据
'…… 代码略,按照通讯协议对串口收到的数据进行分析和处理
RichTextBox1.Text += Convert.ToString(Hex(coldata.Item(xx)))
Next xx
Timer1.Stop()
End If
End If
End Sub
Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
RichTextBox1.Text = ""
End Sub
End Class
'……
'你还是没缓存数据啊。
dim comm as new serialport()
addhandler comm.DataReceived addressof OnComm
private buf as List(of byte)
public sub OnComm(参数不记得了)
dim n as integer = comm.BytesToRead
dim tmp(n) as byte
comm.read(tmp,0,n)
buf.addrange(tmp)
'search buf
for each b as byte in buf
if b = &hAA and buf.count >12 then
'数据完整了
end if
next
end sub