Serial port Read problem (DataReceivedHandler)

I’m using the “System.IO.Ports”
I don’t quite get it but is it because Mono library is not the same implementation as .NET so not everything will be working exactly the same sometimes.

My first issue is DataReceivedHandler does not work at all.
So the other options are ReadLine or Read but these too can lead to Unity Crashing or being stuck and there’s no way to Kill Unity task unless you restart.
ReadExisting sometimes work.

The device I’m connecting to requires RTS/CTS flow control, that means I need Handshake set on RequestToSend and that’s all the changes needed?

So currently I don’t know if there is a stable way to read without getting into some issues.
BTW i tried my app on visual studio and it works fine.
sample of the code i use in unity:

    public static SerialPort sp = new SerialPort("\\\\.\\COM12", 38400, Parity.None, 8, StopBits.One);   

   void Start () 
    {
           print("started!");
           sp.Handshake = Handshake.RequestToSend;
           sp.DataReceived += new SerialDataReceivedEventHandler(DataReceivedHandler);
                    sp.Open();  // opens the connection
                    sp.ReadTimeout = 50;  // sets the timeout value before reporting error
                    sp.WriteTimeout = 500;
                    sp.DtrEnable = false;
}

    private static void DataReceivedHandler(
                        object sender,
                        SerialDataReceivedEventArgs e)
    {
        SerialPort sp = (SerialPort)sender;
        string indata = sp.ReadExisting();
		print(indata);
}

Please search UnityAnswers and/or Google, this issue has been discussed several times before already.

Unfortunately, in the Mono versions Unity uses, things like DataReceivedHandler, ReadExisting, or BytesToRead are not implemented and/or buggy, so you can’t use them.

Read and ReadLine are “blocking” functions, they will pause execution if no data is available , or until a newline is received, respectively.

Your best chance is to move your Read/ReadLine stuff into a separate function, and then run that function in a separate Thread.

Please visit the following web site to view updates on this issue and comment letting the Unity staff know how important this functionality is to the COM Port and TTY reading community! VOICE YOU OPINION!