Results 1 to 6 of 6

Thread: [RESOLVED] SrialPort readbyte to a Byte array failure

  1. #1

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    384

    Resolved [RESOLVED] SrialPort readbyte to a Byte array failure

    Hello all, following code will cause "Index was outside the bounds of the array." as exception:
    Code:
    Public Class MainWindow
        Dim RxBuffer As Byte() = {}
            Try
                If SerialPort1.BytesToRead <> 0 Then
                    For index = 0 To SerialPort1.BytesToRead - 1
                        RxBuffer(index) = SerialPort1.ReadByte
                    Next
                End If
            Catch ex As Exception
                MsgBox(ex.Message, MsgBoxStyle.Critical)
                Application.Exit()
            End Try
    End Class
    What I tried:
    - Switching variable to other type(s).
    - Adding/removing "()" and "{}".
    - Adding/removing "index + 1" and "index - 1".

    Adding "SerialPort1.ReadByte" in a textbox control once a loop works properly for whole data:
    Code:
    TextBox1.Text = TextBox1.Text & SerialPort1.ReadByte & " "
    The goal is to store received bytes in an array to call/change in-application then clear it every time. The length is changeable every time.
    Thanks for contribution in advanced.

  2. #2
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: SrialPort readbyte to a Byte array failure

    If you expect to read N Bytes and assign them to the elements of an array then you need to have an array and you need that array to have at least N elements. Here:
    vb.net Code:
    1. Dim RxBuffer As Byte() = {}
    you are creating an array with zero elements, so of course any index you specify will be out of range. The obvious thing to do is to create an array at the point you know how many elements it will need:
    vb.net Code:
    1. Private buffer As Byte()
    and:
    vb.net Code:
    1. Dim byteCount = SerialPort1.BytesToRead
    2.  
    3. If byteCount > 0 Then
    4.     buffer = New Byte(byteCount - 1) {}
    5.  
    6.     For i = 0 To byteCount
    7.         buffer(i) = SerialPort.ReadByte()
    8.     Next
    9. End If
    Alternatively, use a List(Of Byte) and call Add, letting it grow as required. You can then call ToArray at the end if you specifically need an array.
    Last edited by jmcilhinney; Jun 2nd, 2022 at 02:03 AM.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  3. #3
    Super Moderator jmcilhinney's Avatar
    Join Date
    May 2005
    Location
    Sydney, Australia
    Posts
    111,221

    Re: SrialPort readbyte to a Byte array failure

    That said, why read the data Byte by Byte when the SerialPort has a Read method that will read multiple Bytes at a time? You can either create an array big enough to contain all the data and read it all in one go:
    vb.net Code:
    1. Dim byteCount = SerialPort1.BytesToRead
    2.  
    3. If byteCount > 0 Then
    4.     buffer = New Byte(byteCount - 1) {}
    5.  
    6.     SerialPort.Read(buffer, 0 byteCount)
    7. End If
    or you can use a fixed-size buffer and read the data in chunks. That's how you generally read large data streams or data for which you don't know the size. I'll leave that to you as an exercise, noting that Read will return the number of Bytes read and that being less than the number of Bytes you specified to read means that there's no more data.
    Why is my data not saved to my database? | MSDN Data Walkthroughs
    VBForums Database Development FAQ
    My CodeBank Submissions: VB | C#
    My Blog: Data Among Multiple Forms (3 parts)
    Beginner Tutorials: VB | C# | SQL

  4. #4

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    384

    Re: SrialPort readbyte to a Byte array failure

    Quote Originally Posted by jmcilhinney View Post
    That said, why read the data Byte by Byte when the SerialPort has a Read method that will read multiple Bytes at a time?
    What a fantastic idea! To be honest I didn't give a chance to try 'Read' method once. I'm using Serial Port in an external microcontroller low-level based stream. (Mostly Modbus RTU and creating a 16 bit values from (EvenByte*255)+OddByte)

    Code:
    Private buffer As Byte()
    Rectifies the matter, sir.

    I believe a comma is needed @ line #6 in last code 'Read' argument. 3:')

    Since we got here, Please introduce the best way you know for an always ready to read port. I mean is there any "DataReceived" event or something to use cause I use a 1mS timer to do such thing (If byteCount > 0 Then communication is online and Rx is coming)

  5. #5

    Thread Starter
    Hyperactive Member pourkascheff's Avatar
    Join Date
    Apr 2020
    Location
    LocalHost
    Posts
    384

    Re: SrialPort readbyte to a Byte array failure

    And two more questions:
    1) How to get that "buffer" from "Private buffer As Byte()" length after all work? (.Length.toString and .GetLength doesn't work)
    2) Didn't want to get it from SerialPort1.BytesToRead because I want to figure out what is happening due to exception which is happening when I stream a non-stop data with such message: "Index was outside the bounds of the array.". Is there a way to clear that "buffer" every cycle?

  6. #6
    Powered By Medtronic dbasnett's Avatar
    Join Date
    Dec 2007
    Location
    Jefferson City, MO
    Posts
    9,897

    Re: SrialPort readbyte to a Byte array failure

    My approach to SerialPorts is different than most. I tend to have a small received event handler that accumulates bytes and a separate process that enforces protocol.

    See: https://www.vbforums.com/showthread....=1#post5568506
    My First Computer -- Documentation Link (RT?M) -- Using the Debugger -- Prime Number Sieve
    Counting Bits -- Subnet Calculator -- UI Guidelines -- >> SerialPort Answer <<

    "Those who use Application.DoEvents have no idea what it does and those who know what it does never use it." John Wein

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width