C # Serial Communication - Received Data Lost

The data received in my C # application is lost due to the fact that the collector array is rewritten rather than added.

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

This example pUartData_coverwrites each time new data is received. On some systems, this is not a problem because the data arrives quickly enough. However, on other systems, the data in the receive buffer is not complete. How to add received data to pUartData_c, rather than overwrite it. I am using Microsoft Visual C # 2008 Express Edition. Thank.

+3
source share
3 answers
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());
   }
}
+1
source

pUartData List<char>, .AddRange().

0

I had to read this question 2-3 times before I found out that this is just a problem with the Array append in C #. (Originally, I thought it was a serious serial communication error ... lol)

Good,

You can use the List<>or class to store dynamic data ArrayList. add delete etc. so every time you get data from a serial, just add it to the list.

0
source

Source: https://habr.com/ru/post/1744369/


All Articles