Solved

VB.NET Serial communications and multithreading

Posted on 2010-08-19
7
3,062 Views
Last Modified: 2012-06-27
I have an application that uses the "On Datareceived" event for serial component (VB.NET 2010).

While the program is receiving data from the serial port, if I attempt to move the form while it is receiving I generate a communications error (the reply timer I set up times out).

The program sends a line of text and sets a reply timeout. After timeout, if data is available then it is processed, if not then coms error is indicated.

Though the data return happens in around 30ms (it is single ACK byte), I need to set timer to over 100ms to avoid the movement of the form from interfering with the receive process, but this makes the download very slow.

Is there some way to stop the user being able to move the form around during reception
OR
Some sort of threading arrangement to prevent form movement effecting serial data reception timing
OR
A better way to receive data (I tried to set a longer reply timeout and then inside the Data Received routine setting the timer interval to low value once data arrives so it does not need to wait for the entire timeout period but was not successful.

Thanks in advance for any help or code snippet that shows a better method of handling incoming data.
0
Comment
Question by:orbitcoms
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
7 Comments
 
LVL 96

Expert Comment

by:Bob Learned
ID: 33486241
I would think that a BackgroundWorker would be the easiest way to approach a multi-threading process.  I have to say that I don't quite understand the need for the timer...
0
 
LVL 5

Expert Comment

by:andr_gin
ID: 33624786
1.) If the SerialPort is created in the same thread as the main Form then the events will also be handled in the same form. If Another event is thrown and the handling of this event takes some time the event of your SerialPort is also delayed.

2.) The SerialPort provides the methods Read(buffer,offset,count) and Write(buffer,offset,count). So you can read/write like a stream.

Warning: Like in a stream the count of the Read method is only a maximum value. If data is received the Read method copies all available bytes into the buffer and returns the number of bytes read. If your connection gets terminated sometimes without a reason then this might be the reason.

3.) In my programs I do not drag the SerialPort on the Form from the toolbox. I create the SerialPort in Code with New System.IO.Ports.SerialPort(PortName,BaudRate...)
Then I start a new communication Thread with New Thread(AddressOf THREAD_SerialCommunication)
The THREAD_SerialCommunication is a Sub that handles the communication with the serial port.
0
 

Author Comment

by:orbitcoms
ID: 33625156
Thanks for the useful comment. Would you happen to be able to provide me a snippet of code that shows the setup of the port and datareceived block so that I can understand how it works.

Up until now all my code simply set a timeout and sent a request to the device then after the timeout it looked at what data has been received (adding each incoming received data to a buffer).

Trouble here is the timeout was always set to maximum time and if data returned sooner, the program still waited the entire timeout period. When I attempted to speed up the program without these threads that you use, moving the form during communications reception caused a timeout and invalid data receive.

I also now want to have a system where I can receive data asynchronously without first polling the device (ie. a stream of readings from a test equipment)

thanks in advance

david
0
PeopleSoft Has Never Been Easier

PeopleSoft Adoption Made Smooth & Simple!

On-The-Job Training Is made Intuitive & Easy With WalkMe's On-Screen Guidance Tool.  Claim Your Free WalkMe Account Now

 
LVL 5

Accepted Solution

by:
andr_gin earned 125 total points
ID: 33627075
Ok here is an example application.

The Background Thread reads all data from the serial Port. The DataReceived event is not used at all.
In this case I write all received data to a queue and have a timer displaying it on a RichTextBox.

You can also handle data directly in the thread (for example writing it to a logfile), if you want depending on your application.

The timeout is really a timeout so if you will get data immediately when it is received. If you know that your datablock is smaller than 1024 bytes you can decrease this value.

If you can tell me what you want to do with your program I can give you a more detailed code.
Imports System.IO
Imports System.IO.Ports
Imports System.Text
Imports System.Threading

Public Class Form1
    Private _SerialCommunicationThread As Thread
    Private _DataQueue As Queue = Queue.Synchronized(New Queue())

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        Me._SerialCommunicationThread = New Thread(AddressOf THREAD_SerialCommunication)
        Me._SerialCommunicationThread.Priority = ThreadPriority.AboveNormal
        Me._SerialCommunicationThread.Start()

        TIMER_Main.Enabled = True
    End Sub

    Private Sub THREAD_SerialCommunication()
        Try
            Dim SerialPort As New SerialPort("COM1", 9600, Parity.None, 8, StopBits.One)
            SerialPort.ReadTimeout = 1000
            SerialPort.Open()

            Dim Buffersize As Integer = 1024
            Dim Buffer(Buffersize - 1) As Byte
            Do
                Dim DataRead = SerialPort.Read(Buffer, 0, Buffer.Length)

                Dim BufferCut(DataRead - 1) As Byte
                For i As Integer = 0 To BufferCut.Length - 1
                    Buffer(i) = BufferCut(i)
                Next

                Me._DataQueue.Enqueue(BufferCut)
            Loop
        Catch ex As Exception
            MsgBox("An error has occured:" & vbCrLf & vbCrLf & ex.ToString)
        End Try
    End Sub

    Private Sub TIMER_Main_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles TIMER_Main.Tick
        While Me._DataQueue.Count > 0
            Dim Bytes = Me._DataQueue.Dequeue
            Dim Text = Encoding.Default.GetString(Bytes)

            RTF_Text.AppendText(Text)
        End While
    End Sub
End Class

Open in new window

0
 

Author Comment

by:orbitcoms
ID: 33627681
Thank you very much for the code example: I'll take a detailed look through in the morning. I am interested in as much info regarding reception of Serial data as possible.

Most time the expected packets in my application are very small (20 bytes or less per packet) but packets can come close together (10ms)
0
 
LVL 53

Expert Comment

by:Dhaest
ID: 34049734
This question has been classified as abandoned and is being closed as part of the Cleanup Program.  See my comment at the end of the question for more details.
0

Featured Post

Revamp Your Training Process

Drastically shorten your training time with WalkMe's advanced online training solution that Guides your trainees to action.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
In this post we will learn different types of Android Layout and some basics of an Android App.
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …
Introduction to Processes
Suggested Courses

615 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question