简体   繁体   中英

Serial Communication with Arduino in C#

I am repeatedly reading a serial port that i created using C# (which is easy).

I created a loop to read the serial port (say 50 times after a delay of 50 milliseconds) and read 10 bytes of the serial port after i click the start button on the form and write the read values to console.

    private void buttonStart_Click(object sender, EventArgs e)
    {
        serialPort1.PortName = "COM3";
        serialPort1.BaudRate = 115200;

        serialPort1.Open();
        if (serialPort1.IsOpen)
        {
            buttonStart.Enabled = false;
            buttonStop.Enabled = true;
            //textBox1.ReadOnly = false;
        }


        for (int i = 0; i < 50; i++)
        {
            string input = "AN\n"; // Analog read command for WildThumper (No problems here)


            if (!serialPort1.IsOpen) return;
            serialPort1.Write(input);

            Application.DoEvents();
            System.Threading.Thread.Sleep(50);

        }

    }

the last byte is '*' which is end of string delimiter in my case. Then i combine the read 10 bytes into the 5 values by the following piece of code

    private void serialPort1_DataReceived(object sender, System.IO.Ports.SerialDataReceivedEventArgs e)
    {
       int n = serialPort1.BytesToRead;  // gives me n = 11 (the last one is '*' for end of string)
       byte[] data = new byte[n];
       serialPort1.Read(data, 0, data.Length);
       int[] Values = new int [5];


        for(int i = 0;i<5;i++)
        {
            int value1 = data[0+i*2];
            int value2 = data[1+i*2];

            int value = value1 + value2;
            Values[i] = value;
        }
        string RxString = string.Join(" ", Values.Select(i => i.ToString()).ToArray());
        Console.WriteLine(RxString + Environment.NewLine);
     }

My problem is that when I run the code it does the required task (reading the serial port and displaying the five Values[] ) a few times (5,6 times), then i get an exception which makes my program crash. the exception points to this line in the code.

     int value1 = data[0+i*2];

the debugger says says something like "make sure that data index is not negative, the maximum index is less that index of list size etc etc." The following exception is shown in the console window:

Unhandled Exception: System.IndexOutOfRange Exception: Index was outside the bounds of array.

I don't know what the problem is. Can you have a look at it and tell me what am I doing wrong. I am an electronics major so my idea of programming is minimal.

You need to check n is always 11. There is a chance that it sometimes returns less than 11, in which case you won't have got 10 bytes to read. You'll need to buffer them and call read again until you get all 10 of them.

I would also recommend you check the return value of serialPort1.Read(data, 0, data.Length); because it returns the number of bytes it actually read, rather than the number of bytes you asked it to read.

See the docs here .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM