Avatar of VASILIS PALAVRATZIS
VASILIS PALAVRATZISFlag for Greece

asked on 

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



User generated imageUser generated image
Visual Basic.NET

Avatar of undefined
Last Comment
VASILIS PALAVRATZIS
Avatar of ste5an
ste5an
Flag of Germany image

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

Avatar of VASILIS PALAVRATZIS

ASKER

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
ASKER CERTIFIED SOLUTION
Avatar of ste5an
ste5an
Flag of Germany image

Blurred text
THIS SOLUTION IS ONLY AVAILABLE TO MEMBERS.
View this solution by signing up for a free trial.
Members can start a 7-Day free trial and enjoy unlimited access to the platform.
See Pricing Options
Start Free Trial
Avatar of VASILIS PALAVRATZIS

ASKER

i ll try it. Thank you soooo much !!!!
Avatar of VASILIS PALAVRATZIS

ASKER

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

Avatar of VASILIS PALAVRATZIS

ASKER

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)
Avatar of VASILIS PALAVRATZIS

ASKER

Just all what i need!!! Thank you so much !!!
Visual Basic.NET
Visual Basic.NET

Visual Basic .NET (VB.NET) is an object-oriented programming language implemented on the .NET framework, but also supported on other platforms such as Mono and Silverlight. Microsoft launched VB.NET as the successor to the Visual Basic language. Though it is similar in syntax to Visual Basic pre-2002, it is not the same technology,

96K
Questions
--
Followers
--
Top Experts
Get a personalized solution from industry experts
Ask the experts
Read over 600 more reviews

TRUSTED BY

IBM logoIntel logoMicrosoft logoUbisoft logoSAP logo
Qualcomm logoCitrix Systems logoWorkday logoErnst & Young logo
High performer badgeUsers love us badge
LinkedIn logoFacebook logoX logoInstagram logoTikTok logoYouTube logo