Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations SkipVought on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

DataReceivedEventHandler is called more than once

Status
Not open for further replies.

selimsl

Programmer
Aug 15, 2005
62
0
0
TR
Hi,

I am using System.IO.Ports.SerialPort to communicate with a device. I sent a command to the device then it sends reply to this command. I get the reply from device using DataReceived event of the serialport object. But reply comes with two parts (not everytime but sometimes it comes with two parts). I mean for example reply message is: "0103020001ABDE" but DataReceived is called two times with a time interval. First "010302" comes and then "0001ABDE" comes. But in this situation my code ignore the second part. Below is my code

Code:
 Private InputBuffer As String = Nothing

Code:
Private Function ReceiveSerialData() As String
        '**************************************
        Dim strReturn As String = String.Empty
        '**************************************
        If objSerialPort.IsOpen = Boolean.FalseString Then
            Throw New Exception("55")
        End If
        '**************************************
        objTimer.Enabled = True
        Do While (InputBuffer = Nothing)
            Application.DoEvents()
        Loop
        '**************************************
        objTimer.Enabled = False
        strReturn = InputBuffer
        InputBuffer = Nothing
        '**************************************
        Dim strTemp As String = String.Empty
        For intTemp As Integer = 0 To strReturn.Length - 1
            strTemp &= Hex(Asc(strReturn.Substring(intTemp, 1))).PadLeft(2, "0")
        Next
        strReturn = strTemp
        '**************************************
        Return strReturn
    End Function

Code:
 Private Sub DataReceivedEventHandler(ByVal sender As Object, ByVal e As IO.Ports.SerialDataReceivedEventArgs)
        '**************************************
        Dim spTemp As SerialPort = CType(sender, SerialPort)
        Do While (spTemp.BytesToRead > 0)
            InputBuffer &= spTemp.ReadExisting()
        Loop
        '**************************************
    End Sub

I am waiting untill InputBuffer is not nothing, When I get the first part of the message, the program skip the second part.

Do While (InputBuffer = Nothing)
Application.DoEvents()
Loop

Does anyone can help me about it?

thanks in advance
 

When I put a breakpoint at Do While and wait for a second,
everthing works fine. I think I need a wait function to wait on that position for a while.

Code:
 Do While (InputBuffer = Nothing)
            Application.DoEvents()
        Loop
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top