ArduinityCommunicator.OpenConnection C# (CSharp) Method

OpenConnection() public method

public OpenConnection ( ) : bool
return bool
    public bool OpenConnection()
    {
        try
        {
            serialPort = new SerialPort("\\\\.\\" + portName, serialSpeed);
            serialPort.Open();
            if (serialPort.IsOpen)
            {
                serialPort.ReadTimeout = 1000 / 120; // this is half a unity frame
                serialPort.WriteTimeout = 1000 / 120;
                serialPort.WriteLine("arduinity_check"); // send message to arduino

                string reply = "";

                while (reply == "")
                {
                    reply = serialPort.ReadLine();
                    if (reply != null && reply != "")
                    {
                        if (reply.StartsWith("arduinity_present"))
                        {
                            #if debugSerial
                            Debug.Log("ArduinityCommunicator::OpenConnection(): found arduinity on " + portName);
                            #endif

                            // parse the name
                            arduinoName = reply.Substring(reply.LastIndexOf('_') + 1);

                            return true;
                        }
                        else
                        {
                            #if debugSerial
                            Debug.Log("ArduinityCommunicator::OpenConnection(): got wrong response on " + portName + " " + reply);
                            #endif

                            return false;
                        }
                    }
                }
            }
            else
            {
                #if debugSerial
                Debug.Log("ArduinityCommunicator::OpenConnection(): " + portName + " is not open");
                #endif
                return false;
            }
        }
        #if debugSerial
        catch(Exception e)
        {
            Debug.Log("ArduinityCommunicator::OpenConnection(): exception trying to read from " + portName + " " + e.Message);
            return false;
        }
        #else
        catch
        {
            return false;
        }
        #endif
        return false;
    }

Usage Example

    public static ArduinityCommunicator GetArduinoByPortname(string _portName, int _serialSpeed)
    {
        ArduinityCommunicator arduinoCommunicator = new ArduinityCommunicator(_portName, _serialSpeed);
        if (arduinoCommunicator.OpenConnection())
            return arduinoCommunicator;

        return null;
    }
All Usage Examples Of ArduinityCommunicator::OpenConnection