Receive Serial (string or byte) Data in Visual Basic

0
down vote
favorite
I have a serial device which sends me data at the baudrate of 38400 and i get it like this ?@D00014C000 000. I can see data comes in on a ritchtextbox but what im trying to do is to use some characters from the string in a list box. For example i want characters "14C" appears in the listbox3. I tried the substring and mid function but listbox lidnt work properly and losses characters or confuse them . Here is my code. Any suggestions please?? i am using visual studio express 2012

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports
 
Public Class frmMain
    Dim myPort As Array
    Delegate Sub SetTextCallback(ByVal [text] As String)
  
 
    'Serial Port Receiving Code Starts Here ....
    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        ReceivedText(SerialPort1.ReadExisting())
 
    End Sub
    'Serial Port Receiving Code Ends Here ....
 
    'Serial Port Receiving Code(Invoke) Starts Here ....
    Private Sub ReceivedText(ByVal [text] As String)
        If Me.rtbReceived.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
 
           
 
        Else
            Me.rtbReceived.Text &= [text]
              Dim fine As String = Mid([text], 7, 3)
            Dim list As Integer = ListBox3.Items.Add(fine)
        End If
 
    End Sub
 

End Class

Open in new window



Picture 1Picture2
VASILIS PALAVRATZISElectrical EngineeringAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

ste5anSenior DeveloperCommented:
First of all: be precise.. Does the serial device send strings or bytes? Huge difference. Strings depend in charsets. Bytes not. Luckily it is often US-ASCII (7 bit).

Then much more important: A serial device must be always threated as a streaming device. Thus you need to read data into a buffer and examine its content. And only process entire messages. E.g.

Imports System
Imports System.ComponentModel
Imports System.Threading
Imports System.IO.Ports

Public Class frmMain

    Dim myPort As Array
    Delegate Sub SetTextCallback(ByVal [text] As String)

    Dim buffer As String

    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim datagram As String

        buffer = buffer & SerialPort1.ReadExisting()
        datagram = DequeueDatagram()
        Do While Not datagram Is Nothing
            HandleDatagram datagram
            datagram = DequeueDatagram()
        Loop
    End Sub

    Private Function DequeueDatagram() As String
        Const LINE_FEED As String = Chr(10)
        Dim linefeed As Long
        Dim result As String = Nothing
		
        If (buffer.IndexOf(LINE_FEED) > -1) Then
            linefeed = buffer.IndexOf(LINE_FEED)
            result = buffer.Substring(0, linefeed)
            buffer = buffer.Substring(linefeed + 1)
        End If

        Return result
    End Function

    Private Sub HandleDatagram(ADatagram As String)
        If Me.rtbReceived.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf ReceivedText)
            Me.Invoke(x, New Object() {(text)})
        Else
            Me.rtbReceived.Text &= [text]
            Dim fine As String = Mid([text], 7, 3)
            Dim list As Integer = ListBox3.Items.Add(fine)
        End If
    End Sub

End Class

Open in new window

1
VASILIS PALAVRATZISElectrical EngineeringAuthor Commented:
Thank you so much for your time. I ll try apply your advices. You can see my device setup here on page 26 https://www.stalkerradar.com/sportsradar/documents/011-0093-00_Pro_II_operator_manual.pdf   Its the bE format
0
ste5anSenior DeveloperCommented:
The bE message starts with a Message type = 0x88 and ends with Last Byte ASCII Carriage Return = 0x0D. So you can basically do the same, but you need some housekeeping for the start byte, e.g.

    Private Function DequeueDatagram() As String
        Const CARET As String = Chr(136)
        Const CARRIAGE_RETURN As String = Chr(10)
        Dim caretPosition As Long
        Dim carriageReturnPosition As Long
        Dim result As String = Nothing

        carriageReturnPosition = buffer.IndexOf(CARRIAGE_RETURN)
        If (carriageReturnPosition > -1) Then
            result = buffer.Substring(0, carriageReturnPosition)
            buffer = buffer.Substring(carriageReturnPosition + 1)
            caretPosition = result.IndexOf(CARET)
            If (caretPosition > -1) Then
              ' Only return an entire bE datagram.
              result = result.Substring(caretPosition)
            Else
              ' Without caret it is never a valid bE formatted message.
              ' Thus we drop it here.
              ' TODO: Log invalid datagrams as they may indicate device or transmission errors.
              result = Nothing
            End If
        End If

        Return result
    End Function

Open in new window

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

VASILIS PALAVRATZISElectrical EngineeringAuthor Commented:
i ll try it. Thank you soooo much !!!!
0
VASILIS PALAVRATZISElectrical EngineeringAuthor Commented:
Dear ste5an this is my final hole code. i get nothing when connect to the serial device. Could you please help me ?What i have done wrong?

Imports System
Imports System.Threading
Imports System.IO.Ports
Imports System.ComponentModel


Public Class Form1
    '------------------------------------------------
    Dim myPort As Array
    Dim buffer As String

    Delegate Sub SetTextCallback(ByVal [ADatagram] As String) 'Added to prevent threading errors during receiveing of data
    '------------------------------------------------
    Private Sub Form1_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load

        myPort = IO.Ports.SerialPort.GetPortNames()
        ComboBox1.Items.AddRange(myPort)

        Button2.Enabled = False

    End Sub
    '------------------------------------------------
    Private Sub ComboBox1_Click(sender As System.Object, e As System.EventArgs) Handles ComboBox1.Click
    End Sub
    '------------------------------------------------
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        SerialPort1.PortName = ComboBox1.Text
        SerialPort1.BaudRate = ComboBox2.Text
        SerialPort1.Open()
        End Sub
    '------------------------------------------------

    Private Sub Button4_Click(sender As System.Object, e As System.EventArgs) Handles Button4.Click
        SerialPort1.Close()
        Button1.Enabled = True
        Button2.Enabled = False
        Button4.Enabled = False
    End Sub

    Private Sub SerialPort1_DataReceived(ByVal sender As Object, ByVal e As System.IO.Ports.SerialDataReceivedEventArgs) Handles SerialPort1.DataReceived
        Dim datagram As String

        buffer = buffer & SerialPort1.ReadExisting()
        datagram = DequeueDatagram()
        Do While Not datagram Is Nothing
            HandleDatagram(datagram)
            datagram = DequeueDatagram()
        Loop
    End Sub

   Private Function DequeueDatagram() As String
        Const CARET As String = Chr(63)
        Const CARRIAGE_RETURN As String = Chr(10)
        Dim caretPosition As Long
        Dim carriageReturnPosition As Long
        Dim result As String = Nothing

        carriageReturnPosition = buffer.IndexOf(CARRIAGE_RETURN)
        If (carriageReturnPosition > -1) Then
            result = buffer.Substring(0, carriageReturnPosition)
            buffer = buffer.Substring(carriageReturnPosition + 1)
            caretPosition = result.IndexOf(CARET)
            If (caretPosition > -1) Then
                ' Only return an entire bE datagram.
                result = result.Substring(caretPosition)
            Else
                ' Without caret it is never a valid bE formatted message.
                ' Thus we drop it here.
                ' TODO: Log invalid datagrams as they may indicate device or transmission errors.
                result = Nothing
            End If
        End If

        Return result
    End Function

    Private Sub HandleDatagram([ADatagram] As String)
        If Me.RichTextBox2.InvokeRequired Then
            Dim x As New SetTextCallback(AddressOf HandleDatagram)
            Me.Invoke(x, New Object() {(ADatagram)})
        Else
            RichTextBox2.Text &= ADatagram
            Dim fine As String = Mid(ADatagram, 7, 3)
            Dim list As Integer = ListBox1.Items.Add(fine)
        End If
    End Sub

  

    End Sub

End Class

Open in new window

0
VASILIS PALAVRATZISElectrical EngineeringAuthor Commented:
I find it. Finaly i change the :
Const CARET As String = Chr(136) to Const CARET As String = Chr(63) and
Const CARRIAGE_RETURN As String = Chr(13) to Const CARRIAGE_RETURN As String = Chr(10)
0
VASILIS PALAVRATZISElectrical EngineeringAuthor Commented:
Just all what i need!!! Thank you so much !!!
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Visual Basic.NET

From novice to tech pro — start learning today.

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.