views:

139

answers:

3

Hello. Received data in my C# application is getting lost due to the collector array being over-written, rather than appended.

  char[] pUartData_c;

  private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
  {
     try
     {
        pUartData_c = serialPort1.ReadExisting().ToCharArray();
        bUartDataReady_c = true;
     }
     catch ( System.Exception ex )
     {
        MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
     }
  }

In this example pUartData_c is over-written every time new data is received. On some systems this is not a problem because the data comes in quickly enough. However, on other systems data in the receive buffer is not complete. How can I append received data to pUartData_c, rather than over-write it. I am using Microsoft Visual C# 2008 Express Edition. Thanks.

A: 

If pUartData was a List<char> you could add the incoming chars to the list with .AddRange().

ondesertverge
+1  A: 
private SerialPort sp;
private List<byte> byte_buffer = new List<byte>();    

private void sp_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
   byte_buffer.Clear();

   while (sp.BytesToRead > 0)
   {
      byte_buffer.Add((byte)sp.ReadByte());
   }
}
gmcalab
you could add data in one-shot, instead of a while loop
SysAdmin
that's def true
gmcalab
A: 

I had to read this question 2-3 times before I knew that this is just Array append problem in c#. (Initially I thought this was a serious serial communication error...lol)

Ok,

You could use a List<> or ArrayList class to maintain dynamic data. i.e add remove etc. so each time you recieve data from serial, just add it to the list.

SysAdmin