473,425 Members | 1,714 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,425 software developers and data experts.

Receiving data from serial port

Hello;
I'm having a problem with receiving data from serial port. There's an eventhandler(datareceived) and I'm monitoring the answer from the serial port to a text box in the eventhandler. There's no problem till here. But also I want to use the incoming data to process it in some functions. But when I assign the incoming string(from the ReadExisting() function) to a local variable there are always lots of characters missing. How do I solve this problem? The code is below:

private void port_DataReceived_1(object sender, SerialDataReceivedEventArgs e)
{
InputData = port.ReadExisting();
OutputData = InputData;
Log(InputData);
}

private void Log(string msg)
{
rtfTerminal.Invoke(new EventHandler(delegate
{
rtfTerminal.SelectedText = string.Empty;
rtfTerminal.AppendText(msg);
rtfTerminal.ScrollToCaret();

}));
}
The problem continues if I write "OutputData = InputData;" in the invoke code.
I'm waiting for your help.
Jul 30 '07 #1
8 16486
Plater
7,872 Expert 4TB
The characters are missing because you are either not reading as fast as they are being sent and the buffer overflows OR your program is taking too long to do things and is missing the bytes.
rs232 is tricky buisness.
Try to limit what you do in that eventhandler to almost nothing. Your results should be better.
Jul 30 '07 #2
okay that may be the problem. but when I don't call the invoke method for the texbox or the other controls, there are still missing characters. So the invoke method brings the control back to the thread to what it was created from, then all the characters are shown in the textbox. Is there any method like invoke() for the variables(string,char[]) to call the threads which they were created from?
Jul 30 '07 #3
Plater
7,872 Expert 4TB
I wrote a terminal program once (and have since specialized it) but Here's what I used:

My eventhandler
Expand|Select|Wrap|Line Numbers
  1. private void sp1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
  2.         {
  3.             dataready = true;
  4.         }
  5.  
And then I had the following function and helper function:
Expand|Select|Wrap|Line Numbers
  1. System.IO.Ports.SerialPort sp1;
  2. private string GetData()
  3. {
  4.     string retval = "";
  5.     wantingdata = true;
  6.  
  7.     //attempt to wait for the dataready signal
  8.     DateTime Endwith = DateTime.Now.AddMilliseconds(READ_TIMEOUTMS);
  9.     while ((!dataready)&&(Endwith.CompareTo(DateTime.Now)>0))
  10.     {
  11.     }
  12.     if (!dataready)
  13.     {
  14.         return "Timed out!";
  15.     }
  16.  
  17.     //only allow READ_TIMEOUTMS worth of miliseconds for reading
  18.     //i actually recomend this be redone so that each character read will reset the timeout value
  19.     Endwith = DateTime.Now.AddMilliseconds(READ_TIMEOUTMS);
  20.     //Now start reading data
  21.     retval = ReadSPData();
  22.     //I was searching for the '\r' character to determine when to stop reading
  23.     while ((retval.IndexOf('\r') == -1) && (Endwith.CompareTo(DateTime.Now) > 0))
  24.     {
  25.         retval += ReadSPData();
  26.     }
  27.  
  28.     wantingdata = false;
  29.     if (retval.IndexOf('\r') > -1)
  30.     {
  31.         if (retval != "")//make sure I don;t have any garbage after that '\r'
  32.             retval = retval.Split("\r".ToCharArray(), StringSplitOptions.RemoveEmptyEntries)[0];
  33.         return retval.Trim();
  34.     }
  35.     else
  36.     {
  37.         return "Timed out!";//Not the most descriptive, but I didn't get a '\r' before my READ_TIMEOUTMS value was reached 
  38.     }
  39. }
  40.  
  41. private string ReadSPData()
  42. {
  43.     string retval = "";
  44.     try
  45.     {
  46.         if (dataready)
  47.         {
  48.         retval += sp1.ReadExisting();
  49.         dataready = false;
  50.         }
  51.     }
  52.     catch (Exception ee)
  53.     {
  54.         EAlert(ee, "Reading SerialPort Data");
  55.     }
  56.     return retval;
  57. }
  58.  
I've never had trouble with dropping data, but I never sent massive amount at once either.
Jul 30 '07 #4
There' s still problem in reading data. I am using a datareceived event to show the retunrning values in a textbox. I need to do that and I do. But also I need to assign the answer from the serial port to use it later in some functions. For example some answers starts with "[A1]" so I don't need to assign the answer to a string; but I want to assign the answer from the serial port to a string when it returns "[A4]"+ 16 bytes of data. Also I'm using VS.NET 2005 and there's no reading method including a parameter of timeout. I'm still waiting for help.
Jul 31 '07 #5
Plater
7,872 Expert 4TB
Right, if you look at my data recieved, you'll see I only set a bit in there. Thats because if I did anything else, I was dropping characters.
Modify my read functions to run continuously in another thread or something?
Jul 31 '07 #6
Plater
7,872 Expert 4TB
Is this a command and response situation?
Like does it only send data to you after you send a command?
If so, that makes it immensly easier.
Jul 31 '07 #7
nmsreddi
366 256MB
Is this a command and response situation?
Like does it only send data to you after you send a command?
If so, that makes it immensly easier.
Hello

In your code you are using

port.ReadExisting();

which indicates ,your application will read the data that present at that particular instance of time only ,there may be cases that all the data may not be reached to the port while your reads the existing data,

better try to stop your thread for a particular amount of time
so that you can read the complete data that exist in port buffer

use this slleep before your port.readexisting()

Thread.Sleep(choose some amount of time );

try it out this worksfor you

GoodLuck
Aug 1 '07 #8
Plater
7,872 Expert 4TB
my readexisting is in a loop.
It will keep reading until it is told to stop (i tell it to stop when it reads a '\r')

As I've said, I don't have any trouble with dropped characters with this solution.
Aug 1 '07 #9

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: ^CeFoS^ | last post by:
Hello to everybody, I've done an application that draws in a frame the trajectory of a robot. The robot position is readed through the serial port, and several commands are wrote through the...
7
by: davetelling | last post by:
I'm a newbie that is still struggling with OOP concepts & how to make things work they way I want. Using Visual C# Express, I have a form in which I added a user control to display a graph, based...
8
by: Vivek Menon | last post by:
Hi, I am using a C program to write/read from a serial port. The writing part is working perfectly fine. However, I am not able to read the values correctly and display them. To debug this issue I...
2
by: Quentin | last post by:
I would like to create a serial port listener that starts recording data to a text file as soon as the port starts receiving the data. How do I trigger the program to start running when data is...
2
by: pauland80 | last post by:
Hello, My soft passively listen to a device sending +- 300 bytes of data each second. After several hours of work, the soft abruptly stops receiving data without any error, (while the device...
2
by: colin | last post by:
Hi, Im having a tiresome amount of trouble with using a bluetooth serial link. The receiving end is a bluetooth-rs232 module conected to my embeded system. The PC has a little usb bluetooth...
0
by: zelov | last post by:
Hi, I am creating an interface which contains the listbox(C# .net micro framework). When the listbox item is seletected, it will send a character to the serial port and show a "send command"...
1
by: lutherchp | last post by:
A baffling end to my week! I open my serial port on my Debian PC (Debian version 5.0.1) I have a decent Null Modem lead going to another PC (I'll call it PC#2), with its port open with the same...
4
by: mayaanu | last post by:
I have developed a GUI based application in C# for communicating with a 16 bit littleendian microcontroller device .the device has a serial port interface. 1.my appplication opens a COM port on...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
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
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
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...
1
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The...
0
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?

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.