Reading Serial PortData in Multiple Chunks

yarmiaanuj

Member
Joined
May 21, 2012
Messages
12
Programming Experience
1-3
hello...now i have come with a new problem....the above problem was solved and i got quiet a close result i wanted....
now i am trying to receive 53 bytes in one go but the data is coming in two chunks....and size of each is variable all the time.
below is the code:

 Dim n As Integer = SerialPort1.BytesToRead 
       comBuffer = New Byte(n - 1) {}
        SerialPort1.Read(comBuffer, 0, n)
        comBuffer.Reverse()
        dat = dat & CStr(Hex(comBuffer(0)))
        If Len(dat) = 1 Then
            dat = "0" & dat
        End If
        MsgBox(n)
        TextBox1.Text = TextBox1.Text & Environment.NewLine & dat


the device is sending all 53 bytes at same time, Realterm is showing all of them....but when i tried it on vb.net, the value of 'n' is variable but sums to 53 all the time.
How can i recieve all 53 bytes and display all 53 in textbox1 ???
 
If you have a new problem then you create a new thread. Please keep each thread to a single topic and each topic to a single thread.

The SerialPort.Read method, like so many other Read methods, takes an array, a start index and a maximum data size as parameters and returns the actual amount of data read. Let's say that you know for a fact that you are going to read N Bytes. You would create an array of length N to hold those Bytes. The first time you call Read you would pass the array as the first argument, zero as the second argument and N as the third argument, which means read up to N Bytes and populate the array with those Bytes starting at index zero. The method will read R Bytes, which will be a number greater than zero and less than or equal to N, populate the first R elements of the array and return R.

You can then call Read a second time and pass the same array as the first argument. You have already populate the first R elements so you would pass R as the second argument, i.e. tell the method to start populating the array at index R. You would also pass (N - R) as the third argument, i.e. tell the method to read up to the total number of Bytes to read less the number of Bytes read the first time. That will then populate the rest of the array.

In short that would look like this:
Dim N As Integer 'The total size of the data.
Dim buffer(N - 1) As Byte
Dim R As Integer = mySerialPort.Read(buffer, 0, N)
mySerialPort.Read(buffer, R, N - R)
You will obviously have to expand that out a little because it will involve two DataReceived events but that's the basic idea.
 
Back
Top