Reading 256 byte data from serial port

Muzahidul Islam 0 Reputation points
2023-11-06T10:11:45.9866667+00:00

hi there,

I am making a windows form to read 256 byte data from serial port. the data byte will be shown a combobox. if i sent maximum 32 byte data to serial port, it worked properly. but when it is more than 32 byte like 36 or 40 byte, error data is shown. I also declared serialPort1.ReadBufferSize = 1024;, but same problem happened. Please check the following function of data receiving:

please help to find out the issue. thank you.

        private void serialPort1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
           

                int bytesToRead = serialPort1.BytesToRead;

                if (bytesToRead > 0)
                {

                    byte[] buffer = new byte[bytesToRead];
                    serialPort1.Read(buffer, 0, bytesToRead);

                    // Clear the ComboBox before adding new data
                    if (cboboxs.InvokeRequired)
                    {
                        cboboxs.Invoke(new Action(() =>
                         {
                             cboboxs.Items.Clear();
                         }));
                    }
                    else
                    {
                        cboboxs.Items.Clear();
                    }

                    // Convert the buffer data to a string representation
                    string dataAsString = BitConverter.ToString(buffer);

                    // Add the string representation to the ComboBox
                    if (cboboxs.InvokeRequired)
                    {
                        cboboxs.Invoke(new Action(() =>
                         {
                             cboboxs.Items.Add(dataAsString);
                             cboboxs.SelectedIndex = cboboxs.Items.Count - 1; // Select the last item
                         }));
                    }
                    else
                    {
                        cboboxs.Items.Add(dataAsString);
                        cboboxs.SelectedIndex = cboboxs.Items.Count - 1; // Select the last item
                    }




                }

               


            }
        ```

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,865 questions
Windows 10
Windows 10
A Microsoft operating system that runs on personal computers and tablets.
10,969 questions
Microsoft Graph
Microsoft Graph
A Microsoft programmability model that exposes REST APIs and client libraries to access data on Microsoft 365 services.
11,103 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,503 questions
0 comments No comments
{count} votes