how to wait for data from the serial port

  • Thread starter Thread starter gol
  • Start date Start date
G

gol

Hi,
I'm developing in c# .NetCF 2.0. I have two operations that need to come one
after another(in fact there are more than two but the basic idea is the same).
However, before starting the second, I must read and process the data from
the serial port(which is generated as a result of the first operation).
How to do it?
What is the best way?
What is the easiest way?
Thank you very much
 
Huh? You want to do operation 1, then 2? Then write the code with 1 before
2. I don't understand what the real question is. If you don't want to
block user interface interaction while you wait for the serial port data to
arrive, put the code, with 1 before 2, in a separate thread. This is very
well documented in the help...

Paul T.
 
Hi,

I presume that you are using the built in serial port control
(System.IO.Ports)?

You can use the DataReceived event. Just append newly received data to a
buffer (either an array of Byte or a string), and parse that buffer, in
event subroutine. When you have received an appropriate response, set a
flag (or flags, if there are multiple possible states). In the routine
where you send the command, you can simply sit in a loop and wait for the
flag or flags to indicate the receipt of data. You also can use this loop
to test for a timeout, in case you need to resend the command (Read all of
receive data before you send subsequent commands, to make things "cleaner").

The loop will not block receive data, which is handled by a background
thread in the SerialPort object (likewise, DataReceived executes in the
thread context of this background thread, so it will operate as expected).

Now, a loop is a blocking operation, so your UI will be unresponsive while
it is executing. If this isn't what you want, then you can Invoke a
delegate or thread to send the command and wait.

I have example code for some of these things in my book (VB, of course, but
C# code is similar).

Dick

--
Richard Grier, MVP
Hard & Software
Author of Visual Basic Programmer's Guide to Serial Communications, Fourth
Edition,
ISBN 1-890422-28-2 (391 pages, includes CD-ROM). July 2004, Revised March
2006.
See www.hardandsoftware.net for details and contact information.
 
Back
Top