我正在使用 arduino 板将串行数据传输到 Unity。我使用电路板附带的读取模拟电压样本和调试日志中愉快显示的输出进行了这项工作。
但是,现在当我运行 Unity 时,出现以下错误:
IOException:端口“COM11”不存在。
我已将我的 COM 端口更改为各种数字,但它们都返回相同的错误。
我的串口读取代码是这样的:
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();
}
}
为什么我的 COM 端口会突然决定自行关闭,有什么原因吗?