[英]Read information from a serial port in VB.net 2008
我在磚牆上!
我有一個功能性PCB,可通過串行端口報告溫度。
我可以打開超級終端並接收我想要的所有數據-所以我知道設備正在運行...但是我想創建一個VB應用程序,以便可以使用接收到的數據。
當我運行程序時,出現此錯誤:
System.TimeoutException: The operation has timed out.
at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count, Int32 timeout)
at System.IO.Ports.SerialStream.Read(Byte[] array, Int32 offset, Int32 count)
at System.IO.Ports.SerialPort.InternalRead(Char[] buffer, Int32 offset, Int32 count, Int32 timeout, Boolean countMultiByteCharsAsOne)
at System.IO.Ports.SerialPort.ReadTo(String value)
at System.IO.Ports.SerialPort.ReadLine()
at Temperature.Form1.ReadFromCom() in C:\Documents and Settings\asamuel\Desktop\VB Project Sollutions\Temperature2\Temperature\Form1.vb:line 43
有人可以幫幫我嗎! 我快瘋了!
在超級終端中,數據通過這樣的方式來傳遞:
R V1.0 2002-01-06 20:37:37 C
1 0027.00
2 0027.00
3 0027.06
4 0027.18
1 0027.00
2 0027.00
3 0027.06
4 0027.18
1 0027.00
2 0027.06
我的VB應用程式程式碼如下所示:
Imports System
Imports System.IO.Ports
Imports System.Threading
Public Class Form1
Dim SerialPort1 As New SerialPort
Dim readThread As Thread = New Thread(AddressOf ReadFromCom)
Dim abortThread As Boolean
Public Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
If Button1.Text Is "Start Capture" Then
Try
abortThread = False
SerialPort1.Open()
readThread.Start()
Button1.Text = "Stop Capture"
Catch ex As Exception
MsgBox("Another program is already using COM1." & vbCrLf & vbCrLf & _
"Please try again later", MsgBoxStyle.OkOnly + MsgBoxStyle.Information, "COM1 Not Available")
End Try
ElseIf Button1.Text Is "Stop Capture" Then
abortThread = True
Button1.Text = "Start Capture"
End If
End Sub
Public Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
With SerialPort1
.PortName = "COM1"
.BaudRate = 2400
.Parity = Parity.None
.DataBits = 8
.StopBits = 1
.ReadTimeout = 500
End With
End Sub
Public Sub ReadFromCom()
While abortThread = False
Try
Dim message As String = SerialPort1.ReadLine
updateStatus("Received: " & message)
Catch ex As TimeoutException
updateStatus(ex.ToString)
End Try
End While
End Sub
Public Delegate Sub updateStatusDelegate(ByVal newStatus As String)
Public Sub updateStatus(ByVal newStatus As String)
If Me.InvokeRequired Then
Dim upbd As New updateStatusDelegate(AddressOf updateStatus)
Me.Invoke(upbd, New Object() {newStatus})
Else
TextBox1.Text = newStatus & vbCrLf & vbCrLf & TextBox1.Text
End If
End Sub
End Class
我需要將searialport1.DTREnable設置為true!
現在可以正常工作了-頭痛了2個月了!
您可能希望放棄設計,轉而使用SerialPort-Class的DataReceived-Event()。
如果到達一定數量的數據(我認為是DataReceivedThreshold-Property),則將觸發DataReceived-Event。 但是該事件將在另一個線程上觸發,因此如果嘗試更改任何控件,請確保使用Invoke()。
也許這篇文章可以為您提供幫助。 您需要將open語句更改為
...
open "COM1:" for Input as #1
Input #1, MyString
...
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.