Search code examples
c#serial-communication

C# Serial Communications - Received Data Lost


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.


Solution

  • 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());
       }
    }