System.IndexOutOfRangeException:'索引超出了数组的范围。 C#

时间:2017-05-09 12:58:40

标签: c# .net arrays arduino

我目前正在开发一个项目,我将arduino uno连接到Windows窗体并使用串行通信显示其中的温度。 但是每次编译我的应用程序时都会出现这个奇怪的错误

  

System.IndexOutOfRangeException:'索引超出了数组的范围。

我已正确声明了我的字符串数组。任何人都可以帮我解决这个问题吗?

SERIAL COM ARDUINO (IMAGE)

using System;
using System.Windows.Forms;
using System.Threading.Tasks;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            serialPort1.Open();
        }

        public String[] towTemp = new string[1];
        public Task Tempdisplay()
            {
            //timer1.Start();
            return Task.Factory.StartNew(() =>
            {
                try
                {
                    String tempFromArduino = serialPort1.ReadLine().ToString();
                    towTemp = tempFromArduino.Split(',');
                    CheckForIllegalCrossThreadCalls = false;
                    if (float.TryParse(towTemp[0], out float result1))
                    {
                    result1 = (float)(Math.Round(Convert.ToDecimal(result1), 1));
                    label2.Text = result1.ToString();
                    aGauge1.Value = result1;
                    }
                    else
                    {
                        return;
                    }
                    if (float.TryParse(towTemp[1], out float result2))
                    {
                    result2 = (float)(Math.Round(Convert.ToDecimal(result2), 1));
                    label3.Text = result2.ToString();
                    aGauge2.Value = result2;
                    }
                    else
                    {
                        return;
                    }




                }
                catch (Exception err)
                {
                   MessageBox.Show(err.ToString());
                }
            });
            }

        private async void timer1_Tick(object sender, EventArgs e)
        {

            timer1.Interval = 1000;
           await Tempdisplay();



        }

        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {

            timer1.Stop();
        }

        private void button1_Click(object sender, EventArgs e)
        {

            timer1.Start();
        }
    }
}

1 个答案:

答案 0 :(得分:0)

使用该行towTemp = tempFromArduino.Split(',');覆盖数组,这意味着它现在的长度为0。

在访问它之前检查它的长度。