Click here to Skip to main content
15,917,005 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I am writing a small application which works on serial port when port ("COM10" in my case) receives data it doesn't receive full byte and sometimes it receives some bytes and again receives some bytes. Why it happened?? I want to receive all bytes at one time so that i can do further processing , I just guessed that dataReceived event triggers at every byte but I want to trigger it only when full data comes. please give me suggestions and edit my code if possible .
Thanks everyone!

Here is my code,

C#
public void _serialPort_DataReceived(object sender, SerialDataReceivedEventArgs e)
      {

          for (int p = 0; p >= 0; p++)
          {
                 int dataLength = _serialPort.BytesToRead;
                byte[]  data = new byte[dataLength];

              int nbrDataRead = _serialPort.Read(data, 0, dataLength);

              if (nbrDataRead == 0)
                  return;
              // Send data to whom ever interested
              if (NewSerialDataRecieved != null)
              {
                  NewSerialDataRecieved(this, new SerialDataEventArgs(data));
              }

              for (int i = 0; i < nbrDataRead; i++)
              {
                  Convert.ToChar(data[i]);
              }
Posted

The usual approach is gathering all the bytes available in the DataReceived handler, and append them to a 'receive buffer' where you can process them.
 
Share this answer
 
Comments
Member 11543226 24-Sep-15 6:43am    
that's exactly i want to know how to gather all byte?, because i tried all read methods but not working
CPallini 24-Sep-15 7:01am    
You can get all the 'available' bytes. To get all the bytes, usually you have to wait for several DataReceived events.
You need to keep checking for data available at the input end. When you receive some bytes, you append them to your buffer, and try again. When you have received the correct number of bytes, or some special byte that indicates 'end of data', then you pass it off to be processed.
 
Share this answer
 
Comments
Member 11543226 24-Sep-15 7:50am    
This exactly i want to do can you tell me proper way of checking bytes and store data in buffer
Richard MacCutchan 24-Sep-15 8:03am    
I thought I just did. Start with a Byte Array, and append each group of bytes as you receive them. When you have all the bytes then you process them according to the requirements of your application.
Member 11543226 24-Sep-15 8:09am    
I am new to c# , i dont know how to store bytes in array ,Can you give me example or any link which describes this process ??
Richard MacCutchan 24-Sep-15 8:35am    
I gave you a link in my previous message.
There are several options you can use depending if you want to read the data as a stream of bytes or as a string.

Option 1, read as bytes
(Very crude way that doesn't consider extra data read after end character)
C#
// Buffer used to keep received data between events
private List<byte> receivedData = new List<byte>();
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    // Read available bytes and check for presence of a end byte
    byte[] buffer = new byte[serialPort1.BytesToRead];
    serialPort1.Read(buffer, 0, buffer.Length);
    receivedData.AddRange(buffer);
    if (receivedData.Contains(0x03)) // Only an example of an end byte
    {
        if (NewSerialDataRecieved != null)
        {
            NewSerialDataRecieved(this, new SerialDataEventArgs(receivedData));
            receivedData.Clear();
        }
    }
}


Option 2, Use the NewLine property

Let's say that you want to read strings from the COM port and your strings are separated with, for example, CR+LF.
Then you need to set the NewLine property somewhere in the code.
C#
serialPort1.NewLine = "\r\n";

Then just read line by line and trigger your event for each line.
C#
private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
{
    string receivedData = serialPort1.ReadLine();
    if (NewSerialDataRecieved != null)
    {
        NewSerialDataRecieved(this, new SerialDataEventArgs(receivedData));
    }
}


There are of course several variants of these examples that you can use as well.
 
Share this answer
 
v2
Comments
Member 11543226 25-Sep-15 0:58am    
error occured at line " NewSerialDataRecieved(this, new SerialDataEventArgs(receivedData));" that it only accept byte array at the place of received data.
George Jonsson 25-Sep-15 1:03am    
Well, you have to options:
1. Convert the string into a byte array using ASCIIEncoding.ASCII.GetBytes
2. Add a constructor to the SerialDataEventArgs class that accepts a string as input.
Member 11543226 25-Sep-15 1:47am    
Thanks sir, I am going to use readline method now and it works nice.
George Jonsson 25-Sep-15 2:11am    
Glad it helped you

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900