C# 串行数据丢失?

标签 c# forms serial-port

我学习C#串行。 我编写此代码来接收数据。 当我运行此代码时,另一个设备仅发送一次数据,但该程序接收数据两次或三次以上。 我该如何解决这个问题?

还有很多事情我不知道。请简单解释一下。 我花了一周的时间,因为我无法解决这个问题......:(

 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.
            }
        }

最佳答案

这段代码有问题:

      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[]) 已将字节数组转换为十六进制字符串序列。然后,在 for 循环中,针对收到的每个字节,将此 hexData 字符串添加到 tb_rx(可能是一个文本框)。因此,根据您一次收到的字节数,您确实会得到重复的输出。只需将其更改为:

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;

关于C# 串行数据丢失?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70301287/

相关文章:

linux - 如何检测属于 gsm/3g-modem 的 tty 是数据端口还是控制端口?

c# - 从文本中获取 url

c# - 检查特定点 x,y 是否在矩形内

c# - .NET 反编译器区分 "using"和 "try...finally"

php - 在 PHP 中检测 Ajax

django - 表单不在 Django 中发布

networking - IP 上的 UART - 如何?

c - 接收tcp数据时写入串口

c# - 如果使用IdentityServer4框架实现,如果内部和外部帐户(facebook,twitter)都具有相同的电子邮件地址,则如何合并

javascript 表单验证不阻止 css.submitted 从操作