Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

COM Port cannot be opened Unity

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?

like image 241
N0xus Avatar asked Mar 23 '23 10:03

N0xus


1 Answers

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

like image 130
aubatmaz Avatar answered Mar 25 '23 01:03

aubatmaz