COM Port cannot be opened Unity

2020-07-18 09:08发布

问题:

I'm using an arduino board to communicate serial data into Unity. I had this working using the read analog voltage sample that comes with the board and the output from that happily displayed in the debug log.

However, now when I run Unity i get the following error:

IOException: The port `COM11' does not exist.

I've changed my COM port to be a variety of numbers but they all come back with the same error.

My serial port reading code is thus:

SerialPort stream = null;
string data = "Ready";


private float DataTimer = 2.0f;
private float TimeToCheckStream = 0.1f; // check data every second
public string COMPort = "";
public int baudRate = 9600;



void Awake ()
{       

    stream = new SerialPort(COMPort,baudRate); //originally 9600
    Debug.Log ("Initialized stream");

    LogWriter writer = LogWriter.Instance;
    writer.WriteToLog( COMPort);
}



void Start ()
{
//  LogWriter writer = LogWriter.Instance;
//  writer.WriteToLog("Testing test");

        if ( stream != null )
        {
            if ( stream.IsOpen ) // close if already open
            {
                stream.Close();
                Debug.Log ("Closed stream");
            }

            stream.Open();
            Debug.Log ("Opened stream");
        }

        else
        {
            Debug.Log ("ERROR: Uninitialized stream");
        }

}


void Update ()
{

    if(DataTimer < TimeToCheckStream) 
    {
        DataTimer += Time.deltaTime;
    } 
    else
    {
        DataTimer = 0.0f;

        if ( stream != null )
        {
            if ( stream.IsOpen )
            {
                // if stream is open do things in here
                stream.ReadLine();
                Debug.Log(stream.ReadLine().ToString());
            }
        }

        else
        {
            Debug.Log ("NULL stream");
        }
    }
}



void OnGUI ()
{
    GUI.Label ( new Rect(500,10,300,100), data );
}



void OnApplicationQuit ()
{       

    if ( stream != null )
    {
        stream.Close();
    }
}

Is there any reason as to why my COM port would suddenly decide to close itself?

回答1:

You can access your COM11 with replacing it with \\.\COM11 You must write:

myPort= new SerialPort("\\\\.\\COM11",9600);

Take a look at Microsoft's Website



回答2:

Use following code to check if COM port actually exists:

foreach(string str in SerialPort.GetPortNames())
{
    Debug.WriteLine(string.Format("Existing COM port: {0}", str));
}

You will get a list in your output window, telling you which COM ports do exist.



回答3:

I'm sure that N0xus has moved on by now, but to help others with this error, if you're on OSX, there is no such thing as COM(any number). Instead go into the Arduino software then go to tools>port find what the port is called (Mine is /dev/cu.usbmodem1411) and BOOM you have your port name.