Serial port help

nico123

Member
Joined
Jul 21, 2009
Messages
7
Programming Experience
Beginner
Dear all,
I have done a program using vb2005 to display reading from my microcontroller bs2 board but have encountered some problems. My code are as follows.
VB.NET:
 Dim Stop_Rx As Boolean

    Private Sub btnRead_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnRead.Click

        SerialPort1.Open()

    End Sub

    Private Sub btnStop_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnStop.Click

        Stop_Rx = True

    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim Data As String = SerialPort1.ReadLine
        Dim reading1 As String
        Dim reading2 As String

        reading1 = CDbl(Data.Substring(0, 3))
        reading2 = CDbl(Data.Substring(3, 3))
        txt1.Text = reading1
        txt2.Text = reading2

        If Stop_Rx = True Then
            SerialPort1.Close()
        End If
    End Sub

End Class

I've encounter an error which is, (Cross-thread operation not valid: Control 'txt1' accessed from a thread other than the thread it was created on.)
 
At second glance your code doesn't include any thread creation or execution. Without being able to see the full problem it will be near impossible for me to help. I found this by googling. Hopefully it helps.
 
That one's easy. ;)

The DataReceived-Event is fired from another Thread.

Add this to your code:
VB.NET:
    Public Sub setTxt1Text(ByVal text As String)
        Me.txt1.Text = text
    End Sub

And then replace
VB.NET:
        txt1.Text = reading1
with
VB.NET:
        Me.txt1.Invoke(New Action(Of String)(AddressOf setTxt1Text), New Object() {"yourText"})

Of course, you'll ahve to the same thing with the second textbox.

For further information on this, have a Look at Invoke and MultiThreading.

Bobby
 
Because I am receiving data from my microcontroller. What should my "yourText" be in the Me.txt1.Invoke(New Action(Of String)(AddressOf setTxt1Text), New Object() {"yourText"}) ?? reading1 ???
 
Back
Top