Serial port: DataRecivedHandler issue

TADBABA

New member
Joined
Dec 9, 2020
Messages
3
Programming Experience
Beginner
Hi all, I'm new to C#. I'm doing a project that uses Zedgraph to implement FIR LPF. A PIC chip is used to filter the square wave to sing wave and transfer the data to C# GUI by Bluetooth. When GUI receive the data for a while, it shows:
System.ArgumentException: 'Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.' At: count = sp.Read(buffer, 0, sp.BytesToRead);
Could anyone help me understand why this happen? Thanks!
Code:

DataRecivedHandler:
  private void DataRecivedHandler(object sender, SerialDataReceivedEventArgs e)
        {

            int count = 0;
            // SerialPort sp = (SerialPort)sender;
            sp = (SerialPort)sender;
          if (sp.BytesToRead > 0)
            {
                byte[] buffer = new byte[sp.BytesToRead];
                if(sp.BytesToRead<=buffer.Length)
                {
                    count = sp.Read(buffer, 0, sp.BytesToRead);

                }
               
                Extract_rach_Character(buffer, count);
               
            }
       
           
        }
 
Back
Top Bottom