C# Serial Data Loss?

Viewed 54

i study C# Serial. i write this code to receive Data. when i run this code and another device sent data only once, but the program receives the data twice or more than three times. how can i fix this problem?

There's still a lot I don't know. Please explain it easily. I spent a week because I couldn't solve this problem.... :(

 private void MainForm_Load(object sender, EventArgs e)//main form
        {
            serialPort1.DataReceived += new SerialDataReceivedEventHandler(EventDataReceived);
            CheckForIllegalCrossThreadCalls = false;
                       ........
                       ........
                       ........
        }
                       ........
                       ........
                       ........

void EventDataReceived(object sender, SerialDataReceivedEventArgs e)//this is receiving data method
        {

            int size = serialPort1.BytesToRead;// assign size of receive data to 'int size'

            byte[] buff = new byte[size];// array who assign receiving data(size = int size)
            serialPort1.Read(buff, 0, size);//assign receive data to 'buff'

            string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
            for (int i = 0; i < size; i++)
            {
                tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
                Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
            }
        }
1 Answers

This code is fishy:

      string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
      for (int i = 0; i < size; i++)
      {
           tb_rx.Text = tb_rx.Text + " \r\n " + hexData;
           Thread.Sleep(1000);//When I first encountered the problem, I added it because I thought the interval was too short. But I don't think this is the solution.
       }

BitConverter.ToString(byte[]) already converts the byte array to a sequence of hex strings. In the for loop, you then add this hexData string to tb_rx (probably a textbox) for each byte received. So depending on the number of bytes you receive at once, you do get duplicate output. Just change that to:

string hexData = BitConverter.ToString(buff).Replace("-", " ");//Convert the received data into hexadecimal numbers and store to 'string hexdata'
tb_rx.Text = tb_rx.Text + " \r\n " + hexData;

Related