使用VB.net手动从串口读取

时间:2011-05-30 10:32:13

标签: vb.net serial-port vb.net-2010

我需要使用RS232连接到AND GF 3000电子秤。我已经使用HyperT和AND自己的程序测试了连接,并且它正在运行。现在我正在创建一个VB应用程序来阅读这个东西,到目前为止它实际上正在工作。然而,它在几个部分都非常错误,所以我想优化它。

我之前的阅读命令使用:

Private Sub mscport_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mscport.DataReceived

Dim tmpBuf As String

tmpBuf = mscport.ReadLine 
End Sub

这不是我正在使用的完整版本,但在其他方面有效。但是,退出并重新连接(我正在使用Windows窗体控件)会出现“由于线程退出或应用程序请求而导致I / O操作中止”异常。环顾'网,我从Dick Grier那里找到了原因:http://www.pcreview.co.uk/forums/serial-port-error-o-operation-has-been-abortedbecause-either-thread-exit-application-request-t2781073.html

What this means, almost certainly, is that the SerialPort object attempted
to complete the call to ReadLine after the port has been closed. This can
happen because of the lack of synchronization between UI events which may
cause the port to close, and the background thread in the SerialPort object
that is performing the actual ReadFile operation (this executes as a result
of ReadLine in your delegate).

The problem with ReadLine, and the reason that I DO NOT use it, is that it
blocks until the the line terminating condition occurs -- this may be well
AFTER you have closed the port. Thus the exception.

I prefer simply buffering my own data in a Static or class-level variable
(all ReadExisting and append new data to the buffer) , and testing that
buffer for the vbCrLf terminating characters. If the vbCrLf is found (InStr
or Substring, your choice), then call a delegate to process and display the
data in the buffer. Remember to clear this buffer AFTER you have processed
and displayed its content. If you do this, the exception should be
resolved.

Dick

以前我的应用使用ReadExisting而不是ReadLine进行串行串行连接。后来,当使用USB串行电缆时,ReadExisting不起作用,所以我使用了ReadLine。我想使用USB线,所以我需要找到一种方法来取代ReadLine。现在我对串口没有什么好震动,但是我已经成功地使用ReadChar创建了一个几乎正常工作的代码来替换ReadLhar:

Private Sub mscport_DataReceived(ByVal sender As System.Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles mscport.DataReceived

Dim tmpbuf As String
Dim bytebuffer(17) As Byte
Dim count As Integer = 17
Try
    While count > 0
        bytebuffer(17 - count) = mscport.ReadChar
        'If bytebuffer(17 - count) = vbCrLf Then

        'End If
        'tmpBuf = tmpBuf & mscport.ReadExisting
        count = count - 1
    End While

Catch ex As InvalidOperationException
    MessageBox.Show(ex.Message)
Catch ex As UnauthorizedAccessException
    MessageBox.Show(ex.Message)
Catch ex As System.IO.IOException
    MessageBox.Show(ex.Message)

End Try
tmpbuf = tmpbuf & System.Text.Encoding.ASCII.GetString(bytebuffer, 0, 17)
'tmpBuf = bytebuffer.ToString()
ReceiveData(tmpbuf)

End Sub

新代码的问题:

  1. IO异常仍然存在。有时它会在打开应用程序时触发。即使有所有例外,它仍然没有抓住。

  2. 数据有时会被收到所有混乱。例如,ST 0009.80 g显示为.80 gST 0009.数据以CrLf结束,所以我仍然想着如何在显示之前重新排列它。< / p>

  3. 我知道有更好的方法可以做到这一点,我想不出一个,或者说我的搜索不够。

0 个答案:

没有答案