Unity Game stops responding when serial port is open?
I have a very simple code which opens serial port COM3, and reads data from a timer that I created. There are two buttons, one to open the port and one to close it. However once I open the port, although the timer still updates the text on screen I am no longer able to click the close port button. Please help?
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using TMPro;
using System.IO.Ports;
public class Time : MonoBehaviour
{
public TMP_Text txt;
SerialPort serialPort = new SerialPort("COM3", 9600);
int serial = 0;
void Start()
{
txt = GetComponent<TextMeshProUGUI>();
}
void Update()
{
if (serial == 1) {
serialPort.BaseStream.Flush();
string cubeTime = serialPort.ReadLine();
txt.text = cubeTime;
}
else { /*do nothing*/}
}
public void OpenPort() {
serialPort.Open();
serial = 1;
}
public void ClosePort() {
serialPort.Close();
serial = 0;
}
}
ReadLine is a blocking call until a newline character is received or a timeout happens.
By default, the ReadLine method will block until a line is received. If this behavior is undesirable, set the ReadTimeout property to any non-zero value to force the ReadLine method to throw a TimeoutException if a line is not available on the port.
However the default timeout is set to infinity so it never times out.
The read time-out value was originally set at 500 milliseconds in the Win32 Communications API. This property allows you to set this value. The time-out can be set to any value greater than zero, or set to InfiniteTimeout, in which case no time-out occurs. InfiniteTimeout is the default.
Please note that this is not a Unity question. You should readup more about hardware communication, threads and synchronisation. Also we already have several of these questions asking how to communicate with an arduino or other hardware. Therefore your question will be rejected.
oh ok, thanks! I had tried using timeout but I was still unable to click the button and got concerned by all the errors being thrown by the timeout