Corruption in serial port data in vb.net

343 Views Asked by At

I have created an application in vb.net that sends and receives data over serial port continuously. I form a frame with a few custom parameters needed such as frame number, frame length, actual string. They are separated by special characters like '@', '#', '$' etc. e.g. @#3$21%Hello.There!!&

I have to test this with minimum 1 ms gap between two consecutive frames. The problem I am facing is, when I receive data in a loop back test, a few characters usually go missing. It is counted as a corrupt frame but I am unable to understand why it occurs in loop back test on windows. This frame appears like, @#3$21Hello.The!!& . The receive function is like this.

Private Sub DataReceivedHandler(sender As Object, e As IO.Ports.SerialDataReceivedEventArgs) Handles RXCOMPort.DataReceived

        If e.EventType = SerialData.Chars Then
            If checkFlag = False Then
                '---receive data 
                str &= RXCOMPort.ReadExisting()
                checkFlag = True ' for the thread of processing received data
            End If
        End If
End Sub

Later there will be some micro-controller based hardware which will receive and send data from UART to UART.

1

There are 1 best solutions below

0
On
 If checkFlag = False Then
            '---receive data 
            str &= RXCOMPort.ReadExisting()
            checkFlag = True ' for the thread of processing received data
        End If

What happens if your Handler is executed before you set the checkFlag in your other processing function?

For example, the first Handler callback collects @#3$21%Hello.The

Then you go process. What happens if the Handler is executed BEFORE your processing function is finished with the first batch of data? Will the new serial port data be dropped?

Typically you'd want to put the received data into a circular buffer. Do this operation within the receive handler and only this operation.

In another function or thread do work on the circular buffer. This way, the handler's job is to ONLY put data in the circular buffer and you won't have dropped data.