travisxuworld
2021-10-20 15:09
采纳率: 93.5%
浏览 39

C#Winform如何比对串口发送的数据与接收的数据呢?

我循环了两次,想第一次结束接受到的数据与发送的数据进行比对,如果对的话就继续循环,那要怎么做呢?
这是发送的数据{"c":"run","x":"0","y":"0","z":"0","r":"0","v":"322"}
这是接收的数据{"c":"done"x":"0.0 "y":"0.0 "z":"48"r":"0.0 ","v":"26108"}
在serialPort.Write(sd, 0, sd.Length);后面要怎么写呢?

下面是接收的代码

        void Comm_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            try
            {
                int len = serialPort.BytesToRead;
                Byte[] InputBuf = new Byte[len];
                serialPort.Read(InputBuf, 0, len);
                ASCIIEncoding encoding = new ASCIIEncoding();
                data = encoding.GetString(InputBuf);
                new Thread(SetReceiveData).Start();
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message, "错误提示", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
        }
        public void SetReceiveData()
        {
            lock (this)

                Invoke(new MethodInvoker(delegate ()

                {

                    this.txtReceive.AppendText(data);

                }));

        }

这是发送的代码

private void btnSend_Click(object sender, EventArgs e)
        {
            byte[] sendData = null;
            byte[] sd = null;
            byte[] datacoding = null;
            if (!serialPort.IsOpen) //如果没打开
            {
                MessageBox.Show("请先打开串口!", "Error");
                return;
            }

            String strSend = txtSend.Text;
            try
            {
                for(int i=1;i<=2;i++)
                {
                    string valuex = @""""+ini.IniReadValue("坐标值" + i, "x")+ @"""";
                    string valuey = @""""+ini.IniReadValue("坐标值" + i, "y")+ @"""";
                    string valuez = @""""+ini.IniReadValue("坐标值" + i, "z")+ @"""";
                    string valuer = @""""+ini.IniReadValue("坐标值" + i, "r")+ @"""";

                    sd = Encoding.UTF8.GetBytes(@"{""c"":""run""," + @"""x"":" + valuex + "," + @"""y"":" + valuey + "," + @"""z"":" + valuez + "," + @"""r"":" + valuer + "," + @"""v"":""322""}");
                    serialPort.Write(sd, 0, sd.Length);
                    textBox12.AppendText(valuex);
                    Thread.Sleep(10000);          

                }
                sd = Encoding.UTF8.GetBytes(@"{""c"":""run"",""x"":""0"",""y"":""0"",""z"":""0"",""r"":""0"",""v"":""322""}");
                serialPort.Write(sd, 0, sd.Length);

            }
            catch (Exception ex)
            {
                MessageBox.Show("Error:" + ex.Message, "Error");
            }

        }
        

  • 写回答
  • 好问题 提建议
  • 追加酬金
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • 於黾 2021-10-20 15:20
    已采纳

    你是对等网络吗,对方会随时随地给你发数据吗,如果不是,别用Comm_DataReceived事件去接收,直接在write之后写个sleep,然后receive
    否则即使你接收到了数据,也要自己解决分包拆包,如何去跟发送的数据去匹配,一大堆麻烦

    评论
    解决 无用
    打赏 举报

相关推荐 更多相似问题