简体   繁体   中英

C# port_DataReceived doesn't work correctly

I have an arduino & c# project. I have a port_DataReceived listener. In normally, It works correctly. But whenever I close serialPort1 and open it again, it gives me an error.

Here is the listener:

void port_DataReceived(object sender, SerialDataReceivedEventArgs e)
{
    if (connect)
    {
        for (int i = 0; i < (10000 * serialPort1.BytesToRead) / serialPort1.BaudRate; i++);
        //Delay a bit for the serial to catch up
        String comingValue = serialPort1.ReadExisting();
        Console.WriteLine(comingValue); 
        String rslt = comingValue[0].ToString(); // This line give me an error
    }
}

Here is the Error:

An unhandled exception of type 'System.IndexOutOfRangeException' occurred in WindowsFormsApplication1.exe

I am checking the comingValue both times it is 11 . first time it works but second time it doesn't work. I don't know why. If somebody know why, please help me. Thanks.

You should check if the string IsNullOrEmpty() . You're trying to read the first character by index. When there is not data in the comingValue . You'll get an index out of bounds. Only read the first char when there is actually one (or more)

String comingValue = serialPort1.ReadExisting();
Console.WriteLine(comingValue); 
String rslt = "";
if(!string.IsNullOrEmpty(comingValue))
    rslt = comingValue[0].ToString();

This is a bad practice thingy to use for a delay...

for (int i = 0; i < (10000 * serialPort1.BytesToRead) / serialPort1.BaudRate; i++);

This will run different on other computers. Try Thread.Sleep(10); or something.

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