3

I am trying to Open a SerialPort in unity. It is working in editor and mono build. But when I build the game with iL2CPP scripting backend. It is throwing an exception with message The port \\.\COM3 does not exist.

Is this something related to Unity IL2CPP build?

Unity player settings:

Scripting Runtime Version: .Net 4.x Equivalent

API compatibility Level: .NET 4.x

public void OpenSerialPort()
{
    try
    {
        string ComPort = @"\\.\COM3"; //I even tried "COM3"
        int BaudRate = 9600;
        // Initialise the serial port
        SerialPort = new SerialPort(ComPort, BaudRate);
        SerialPort.ReadTimeout = ReadTimeout;
        SerialPort.WriteTimeout = WriteTimeout;
        SerialPort.DtrEnable = true;
        SerialPort.RtsEnable = true;
        // Open the serial port
        SerialPort.Open();

        Debug.LogError("SerialPort successfully opened!");
    }
    catch (UnauthorizedAccessException ex)
    {
        // Failed to open com port or start serial thread
        Debug.LogError("UnauthorizedAccessException: " + ex.Message.ToString());
    }
    catch (ArgumentOutOfRangeException ex)
    {
        // Failed to open com port or start serial thread
        Debug.LogError("ArgumentOutOfRangeException: " + ex.Message.ToString());
    }
    catch (ArgumentException ex)
    {
        // Failed to open com port or start serial thread
        Debug.LogError("ArgumentException : " + ex.Message.ToString());
    }
    catch (InvalidOperationException ex)
    {
        // Failed to open com port or start serial thread
        Debug.LogError("ArgumentException : " + ex.Message.ToString());
    }
    catch (IOException ex)
    {
        // Failed to open com port or start serial thread
        Debug.LogError("IOException : " + ex.Message.ToString());
    }
} 
djkpA
  • 1,224
  • 2
  • 27
  • 57
  • I read somewhere that \\.\ format is for two-digit ports – Bizhan Aug 15 '18 at 08:47
  • I event tried just "COM3". same exception – djkpA Aug 15 '18 at 08:54
  • check this out : https://stackoverflow.com/a/18796383/366064 – Bizhan Aug 15 '18 at 09:02
  • In my case I am sure that com port exists .. because I am checked in Device Manager – djkpA Aug 15 '18 at 09:05
  • 2
    @djkp Windows often doesn't handle COM ports too well. Just because it shows in device manager doesn't mean its actually there. For example, often if you change a COM port number in device manager, it will show immediately, but will not be available until after a reboot. I work a lot with USB Serial ports from FTDI and find FTDI's FTPROG utility much more reliable to determine if a port is actually present. – Andy P Aug 15 '18 at 09:18
  • 1
    Yeah I tried printing port as suggested by @Bijan. It prints COM3 – djkpA Aug 15 '18 at 10:28

0 Answers0