cszoudnx2
cszoudnx2
采纳率100%
2019-08-26 16:16

C# 串口接收抛出索引超出数组界限

已采纳

求助大佬!感谢!
1、只要串口接收到的数据流中存在0x1A,就会抛出“索引超出数组界限”。

2、关键代码如下:

  private void Form1_Load(object sender, EventArgs e)
        {
            sp1.Parity = Parity.None;
            sp1.BaudRate = int.Parse("9600");
            sp1.ReceivedBytesThreshold = 5; //设置触发字节数
            //---------------------------------------------------------------------
            Control.CheckForIllegalCrossThreadCalls = false;    //
            sp1.DataReceived += new SerialDataReceivedEventHandler(sp1_DataReceived);  //串口接收事件

            sp1.DtrEnable = true;
            sp1.RtsEnable = true;

            sp1.ReadTimeout = 1000;
             sp1.Close(); 
        }
private void button_open_Click(object sender, EventArgs e)
        {
            try
            {
                sp1.Open();
            }
            catch
            {
                sp1.Close(); 
                MessageBox.Show("没有此串口!");
            }
        }
 void sp1_DataReceived(object sender, SerialDataReceivedEventArgs e)
        {
            if (sp1.IsOpen)     
            {
                byte[] byteRead = new byte[sp1.BytesToRead];  //获取串口接收缓冲区中字节数
                try
                {
                    Byte[] receivedData = new Byte[sp1.BytesToRead];   
                    sp1.Read(receivedData, 0, receivedData.Length);
                    this.Invoke(new EventHandler(delegate
                    {
                        textBox1.Text = Convert.ToString(receivedData.Length); 
                    }));

                   sp1.DiscardInBuffer();   //clear
                    //-------------------------------------------------
                    if (receivedData[0] == 0xAA && receivedData[1] == 0x55)
                    {
                        string Recostr = string.Empty;
                        if (DataType == 0)
                            Recostr = "Hex: " + arr2string(receivedData, 0, receivedData.Length);
                        else
                            Recostr = "Dec: " + arr2string(receivedData, 0, receivedData.Length);

                        RecodLine = DateTime.Now.ToString("G") + " " + Recostr;

                        this.Invoke(new EventHandler(delegate
                        {
                            listBoxAutoRefesh(RecodLine);
                        }));

                        receok = true;

                    }

                }
                catch (System.Exception ex)
                {
                    sp1.DiscardInBuffer();  
                    MessageBox.Show(ex.Message, "出错提示");

                }
            }
        }

3、现象截图如下:
图片说明

4、接收数据流验证过百来个字节,经实验,只要数据流中任何位置存在0x1A,都会抛出“索引超出数组界限”异常。

  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • tansh4731 迷途小T 2年前

    //0x1A会触发一次中断,接收两次,第一次EOF,第二次才是数据;
    if (receivedData[0] == 0xAA && receivedData[1] == 0x55)
    //你这个判断有问题,如果有一次收到了一个字节数据,“索引超出数组界限”异常。

    点赞 评论 复制链接分享