473,386 Members | 1,602 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,386 software developers and data experts.

SerialPort and SerialDataReceivedEventHandler help

I have the following method that handles the data received event:
private void _port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string data = _port.ReadExisting();
_log.LogToFile(data, true);
}

The LogToFile function logs data to a file. The second parameter
indicate if the file should timestamp the message.

On the initial test of this method I got the following result:
[9/19/2008 4:40:04 PM]10??I 1
[9/19/2008 4:40:04 PM] 1909081
[9/19/2008 4:40:04 PM]640?

This is not what I expected. I converting an old VB 6.0 program to
C#. If I add Thread.Sleep(500) before the ReadExisting() I get the
string I was expecting:
[9/19/2008 4:57:47 PM]10??I 1 1909081657?

Notice in the first try it is sending 8 bytes at a time. Is there
anyway to avoid using Thread.Sleep to achieve this?
Sep 25 '08 #1
8 6458
hi Kevin,

Ke***********@gmail.com wrote:
On the initial test of this method I got the following result:
[9/19/2008 4:40:04 PM]10??I 1
[9/19/2008 4:40:04 PM] 1909081
[9/19/2008 4:40:04 PM]640?

This is not what I expected. I converting an old VB 6.0 program to
C#. If I add Thread.Sleep(500) before the ReadExisting() I get the
string I was expecting:
[9/19/2008 4:57:47 PM]10??I 1 1909081657?
The first result looks good. I don't know, what device you are querying,
but your string has obviously an explicit start and end symbol. Just
read it in a loop as long as your string is not complete.
mfG
--stefan <--
Sep 25 '08 #2
hi,

Stefan Hoffmann wrote:
The first result looks good. I don't know, what device you are querying,
but your string has obviously an explicit start and end symbol. Just
read it in a loop as long as your string is not complete.
Better than a loop (i'm using <as start/end tags):

private string _Data = null;
private void _port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string data = _port.ReadExisting();

if (_Data == null && data.StartsWith("<"))
{
_Data = data;
data = null;
}
if (_Data != null && data != null)
_Data += data;
if (_Data != null)
if (_Data.EndsWith(">"))
{
_log.LogToFile(_Data, true);
_Data = null;
}
}

Depending on the kind of device, you must consider that you get strings
like "789><123897"
mfG
--stefan <--
Sep 25 '08 #3
I tried that. There is still only 8 bytes available at a time. The
only solution I have found so far is to add the sleep. I don't want
to do that because then I have to make the sleep long enough to get
the larger messages but not so large any timeouts will be triggered.
Sep 25 '08 #4
On Sep 25, 9:51*am, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
hi,

Stefan Hoffmann wrote:
The first result looks good. I don't know, what device you are querying,
but your string has obviously an explicit start and end symbol. Just
read it in a loop as long as your string is not complete.

Better than a loop (i'm using <as start/end tags):

private string _Data = null;
private void _port_DataReceived(object sender,
* *SerialDataReceivedEventArgs e)
{
* *string data = _port.ReadExisting();

* *if (_Data == null && data.StartsWith("<"))
* *{
* * *_Data = data;
* * *data = null;
* *}
* *if (_Data != null && data != null)
* * *_Data += data;
* *if (_Data != null)
* * *if (_Data.EndsWith(">"))
* * *{
* * * *_log.LogToFile(_Data, true);
* * * *_Data = null;
* * *}

}

Depending on the kind of device, you must consider that you get strings
like "789><123897"

mfG
--stefan <--
That's interesting. What isn't being displayed in my post is the
start and end character - 0x02 and 0x03.
Sep 25 '08 #5
hi Kevin,

Ke***********@gmail.com wrote:
I tried that. There is still only 8 bytes available at a time.
Try setting another bit (baud) rate for your port.
mfG
--stefan <--
Sep 26 '08 #6
Ke***********@gmail.com wrote:
I have the following method that handles the data received event:
private void _port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string data = _port.ReadExisting();
_log.LogToFile(data, true);
}

The LogToFile function logs data to a file. The second parameter
indicate if the file should timestamp the message.

On the initial test of this method I got the following result:
[9/19/2008 4:40:04 PM]10??I 1
[9/19/2008 4:40:04 PM] 1909081
[9/19/2008 4:40:04 PM]640?

This is not what I expected. I converting an old VB 6.0 program to
C#. If I add Thread.Sleep(500) before the ReadExisting() I get the
string I was expecting:
[9/19/2008 4:57:47 PM]10??I 1 1909081657?

Notice in the first try it is sending 8 bytes at a time. Is there
anyway to avoid using Thread.Sleep to achieve this?
If you know the minimum length of an incoming message, then you could change the
ReceivedBytesThreshold property of the SerialPort. Or, if your incoming message
contains a known end byte that you can synch on, you could use the ReadTo()
method.

HTH,
-rick-
Sep 26 '08 #7
I cannot change the baud rate, I have to match the machine, right?
The minimum number of characters could be one. The machine sends an
ACK once and a while to see if anything is listening. This is
receiving data from a medical device. There is a comments field that
can be filled out and that will be in the data stream

I said VB but that was my mistake. It's a service that uses Vb to
manage it. The code that monitors the serial port is C++. here's the
C++ code:
if(ReadFile(hComm,buf,4096,&dwBytesTransferred,NUL L) == TRUE)

That will read the entire stream into the buffer.

Someone suggested to me to use SerialPort.ReadLine. None of these
make a difference. First, there may be new line characters in the
data stream that is part of the data. I've tried all of the read
functions, the program is only getting 8 bytes at a time unless I put
a sleep in there.

I have even tried something like
while (_port.BytesToRead 0)
{
iRead = _port.Read(buffer, iRead, _port.BytesToRead);
iTotal += iRead;
}

Only the first 8 bytes unless I put a sleep in the loop. A sleep
probably isn't bad, it just has to be large enough that on slower
machines it will still get all the data into the buffer but not so
long that it causes any timeouts.

I think I have to do what Stefan suggested if I want to be safe.

BTW, thanks for the responses. I tried to get a response on the msdn
forum but apparently my question was off topic for the general C#
forum.
Sep 26 '08 #8
Ke***********@gmail.com wrote:
On Sep 25, 9:51 am, Stefan Hoffmann <stefan.hoffm...@explido.de>
wrote:
>hi,

Stefan Hoffmann wrote:
>>The first result looks good. I don't know, what device you are querying,
but your string has obviously an explicit start and end symbol. Just
read it in a loop as long as your string is not complete.
Better than a loop (i'm using <as start/end tags):

private string _Data = null;
private void _port_DataReceived(object sender,
SerialDataReceivedEventArgs e)
{
string data = _port.ReadExisting();

if (_Data == null && data.StartsWith("<"))
{
_Data = data;
data = null;
}
if (_Data != null && data != null)
_Data += data;
if (_Data != null)
if (_Data.EndsWith(">"))
{
_log.LogToFile(_Data, true);
_Data = null;
}

}

Depending on the kind of device, you must consider that you get strings
like "789><123897"

mfG
--stefan <--

That's interesting. What isn't being displayed in my post is the
start and end character - 0x02 and 0x03.
Then, again I will suggest ReadTo(). It looks as if your data may consist of a
fixed length ASCII string bracketed by start and end framing values. You could
use ReadTo() to read up to the next start byte, as per

string startPattern = Encoding.ASCII.GetString(new byte[]{2});
string input, junk;
while (1)
{
/*
Read previous previous input through end byte
(should be 20 bytes as per your example). Then
read and discard the start byte you just found.
*/
input = myPort.ReadTo(startPattern);
junk = myPort.ReadByte(); //
}

If your data pattern is as simple as you indicate then this simple loop or
something very like it may work for you. You would probably want to add
validation of the start and end bytes plus code to recover your framing if you
happen, e.g., to get a short input string.

HTH,
-rick-
Sep 27 '08 #9

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

0
by: Nathan Ie | last post by:
Hi there! Not sure how many of you out there are familiar with the Serialport Class, but I'm trying to add an event handler for every time I receive new incoming data from the serial port by...
3
by: Nathan Ie | last post by:
Hello all! I was wondering if any of you could shed some light on this problem I cant seem to figure out... I try to add an event handler to my SerialPort variable by doing: ...
0
by: LordHog | last post by:
Hello all, I would like to use the new SerialPort class in Visual C++ 2005 Express edition, but I am having problems adding my event handler to the DataReceived event. In the header file I have...
2
by: Andrea Judge | last post by:
Hi there, I'm developing an application to catch OBD sensors' data from my car. I connect it via a RS232 interface. Now. with HyperTerminal I can connect and send/receive data, but I'd like to...
13
by: Jean Paul Mertens | last post by:
Hello, Someone can tell me why I dont get serial port events in a Service, I created a separate Thread to open the port but no events are coming up (the same happens when I use the timer...
7
by: Simon | last post by:
Hi all, I'm writing a PocketPC / CE application which communicates with a Bluetooth GPS reciever that is paired to a serial port but I'm experiencing odd behaviour from the CF 2.0 SerialPort...
3
by: Adriano | last post by:
Hello, I'm developing an application in VB.NET 2005 that communicates with a device through RS232, and need to send the following sequence of hexadecimal data to the device: 0xFF, 0x01, 0xC3,...
1
by: Lars Siden | last post by:
Hi, I've really struggled with this. Using Hyperterminal everything works fine. But if I write my own program I can't get "OnDataReceived" to be fired. MS samples from the SDK gives me the...
0
by: cronusf | last post by:
I set up two virtual COM ports 3 and 4 using com0com. I tried to test it with the following program. However, the DataReceived event handlers never get called. Can anyone with SerialPort class...
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.