-
Serial Port buffer
Hi Everyone
I'm trying to receive data from a serial port. I can do this quite fine when its just strings I'm receiving, but
this I need to receive bytes. The following code only allows for the first byte to receive then falls over
with
"An exception of type 'System.IndexOutOfRangeException' occurred in mk3CommTest.exe but was not handled in user code"
error. I have commented out the try statement so I see the error
Any help would be appreciated
Code:
Private Sub SerialPort1_DataReceived(sender As Object, e As SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
'Handles serial port data received events
UpdateFormDelegate1 = New UpdateFormDelegate(AddressOf UpdateDisplay)
Dim n As Integer = SerialPort1.BytesToRead
comBuffer = New Byte(n - 1) {} 'buffer
SerialPort1.Read(comBuffer, 0, n) 'read data from the buffer
Me.Invoke(UpdateFormDelegate1) 'delegate
End Sub
Private Sub UpdateDisplay()
' Try
RvdTxtBox.Text = CStr(comBuffer(0))
' Catch ex As Exception
' End Try
End Sub
-
Re: Serial Port buffer
I don't know specifically what the issue is, but I'm pretty sure it is related to you setting comBuffer to a new byte array in one thread, and trying to process comBuffer in your Gui thread.
Sometimes, the reference to comBuffer, or even the contents of comBuffer are going to change before your UpdateDisplay gets to the line where it references comBuffer.
You should probably push the bytes into a concurrent Queue, or setup a comBuffer where you treat it as a ring buffer and don't (essentially) recreate the buffer each time you write to it. You would just insert data into the buffer at a location you track with a "head" (or tail pointer depending on your perspective), and read from the buffer, keeping track of what you've read with a "tail" pointer (or "head" if your perspective is reversed).
-
Re: Serial Port buffer
Click on the serial port link in my signature. It does what passel suggests and should be helpful I hope.
-
Re: Serial Port buffer
Thanks for your help guys ill give it a go