Read Serial Port Byte and put in array

ejleiss

Active member
Joined
Oct 1, 2012
Messages
37
Programming Experience
1-3
Hi I am trying to read a frame of 400 bytes from a serial port and place them into an array so I can pick and choose which bytes I am interested in or not.
Basically I am using SerialPort1.ReadByte() to read each byte one by one. I really am only interested in the 11th and 12th bytes in the 400 byte frame, so what I would like to do is set up a counter which reads in a byte and increments the "ByteCount" and then when ByteCount is equal to 11 I would like to save that value and do the same for ByteCount 12.

I am having a hard time with this and was wondering if someone could help me out.
Thank you.
 
Hi,

You have not posted exactly how you are coding your com port so I have taken this example straight of the Microsoft MSDN website and added a few bits to demonstrate what you could do here:-

SerialPort.DataReceived Event (System.IO.Ports)

VB.NET:
Imports System
Imports System.IO.Ports
 
Public Class Form1
  Private mySerialPort As New SerialPort("COM1")
  Private indata As String
 
  Private Sub Form1_FormClosing(sender As Object, e As System.Windows.Forms.FormClosingEventArgs) Handles Me.FormClosing
    CloseComPort()
  End Sub
 
  Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
    OpenComPort()
  End Sub
 
  Private Sub OpenComPort()
    mySerialPort.BaudRate = 9600
    mySerialPort.Parity = Parity.None
    mySerialPort.StopBits = StopBits.One
    mySerialPort.DataBits = 8
    mySerialPort.Handshake = Handshake.None
    AddHandler mySerialPort.DataReceived, AddressOf DataReceivedHandler
 
    Try
      mySerialPort.Open()
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try
  End Sub
 
  Private Sub CloseComPort()
    Try
      mySerialPort.Close()
    Catch ex As Exception
      MsgBox(ex.Message)
    End Try
  End Sub
 
  Private Sub DataReceivedHandler(sender As Object, e As SerialDataReceivedEventArgs)
    Dim mySP As SerialPort = CType(sender, SerialPort)
    Dim ElevenPosValue As String = String.Empty
    Dim TwelvePosValue As String = String.Empty
 
    indata += mySP.ReadExisting()
 
    If indata.Length >= 11 Then
      ElevenPosValue = indata.Substring(10, 1)
      If indata.Length > 11 Then
        TwelvePosValue = indata.Substring(11, 1)
      End If
      'do whatever you need to do with the values extracted from the inbound string
      'also consider what needs to be done with the inbound string in readiness
      'for the next data received event.
    End If
  End Sub
End Class
Hope that helps.

Cheers,

Ian
 
Back
Top