Solved

VB.NET Serial communications and multithreading

Posted on 2010-08-19
7
2,709 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
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
Free Trending Threat Insights Every Day

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

 
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

What Is Threat Intelligence?

Threat intelligence is often discussed, but rarely understood. Starting with a precise definition, along with clear business goals, is essential.

Join & Write a Comment

This is about my first experience with programming Arduino.
Whether you’re a college noob or a soon-to-be pro, these tips are sure to help you in your journey to becoming a programming ninja and stand out from the crowd.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …

760 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

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now