• 主页
  • VBS
  • .NET技术
  • VBA
  • VB网络编程
  • VB多媒体
  • VB数据库
  • VB控件
  • VB COM/DCOM
  • VB基础类
  • VB API
yueyangyxj 2009年10月29日
获取串口数据问题
我想通过串口获取数据,发过来的数据长度是8位,端口数据是一个数字一个数字发过来的,并且是反序的,如发送数据123.5和125.5则是按如下数据发送:5.321000=5.521000=。
程序代码如下:
1、打开串口
If (SerialPort1.IsOpen = True) Then SerialPort1.Close()
SerialPort1.PortName = "com1"
SerialPort1.BaudRate = 1200
SerialPort1.DataBits = 8
SerialPort1.Parity = Parity.None
SerialPort1.StopBits = StopBits.One
SerialPort1.ReadTimeout = 2000
SerialPort1.ReceivedBytesThreshold = 1
SerialPort1.Open()
AddHandler SerialPort1.DataReceived, AddressOf SerialPort1_DataReceived

2、获取数据
Private Sub SerialPort1_DataReceived(ByVal sender As System.Object,
ByVal e As System.IO.Ports.SerialDataReceivedEventArgs)
If e.EventType <> SerialData.Chars Then Exit Sub
isReceiving = True ';//开始读
Dim inData As String = SerialPort1.ReadExisting
DispalyText(inData)
isReceiving = False ';//开始读
End Sub

Delegate Sub SetTextCallback(ByVal InputString As String)

Private Sub DispalyText(ByVal comData As String)
If Me.txtReceive.InvokeRequired Then
Dim d As New SetTextCallback(AddressOf DispalyText)
Me.Invoke(d, New Object() {comData})
Else
If comData.Trim = "=" Then
Me.txtReceive.Text = ""
Else
Dim GetComData As String = comData
If GetComData.Length > 8 Then
Dim weight() As String = GetComData.Split("=")
For i As Integer = 0 To weight.Length - 1
Me.txtReceive.Text = weight(i)
If IsNumeric(StrReverse(txtReceive.Text)) Then
If Convert.ToDouble(StrReverse(txtReceive.Text)) > 0 Then
txtSend.Text = txtReceive.Text
End If
Else
txtSend.Text = 0
End If
Next
Else
Me.txtReceive.Text = GetComData + Me.txtReceive.Text
If txtReceive.Text.Length = 8 Then
txtSend.Text = txtReceive.Text.Substring(3)
End If
End If
End If
End If
End Sub

我的处理方式是把接收到的数据一个一个加起来,判断当前是不是等于8位(想去两个“=”号之间的数据),发现这样处理效率很低,程序很容易出错,不知道是什么原因?调试的时候发现comData数据有时候会有很多,并不是一个数据,不知道是什么原因?
...全文
287 点赞 收藏 5
写回复
5 条回复

还没有回复,快来抢沙发~

发动态
发帖子
VB
创建于2007-09-28

1.1w+

社区成员

11.0w+

社区内容

VB技术相关讨论,主要为经典vb,即VB6.0
社区公告
暂无公告