So, i’ve gotten my hands on an arduino and have been messing around with it for some hours.
i’ve run into a problem though, one that i cannot solve and the people around me who knows something about an arduino as well have no idea how to fix it either, thats why im coming here.
The problem is: Unity either freeze or the connection does a timeout whenever i try to run the script and send some data from the arduino to unity, here are my scripts, unity first:
public class SerialPortListener : MonoBehaviour {
public static string COMPort = "COM3";
public bool portOpen = false;
public SerialPort serialPort = new SerialPort(COMPort,9600);
public bool errorHandling = false;
public string incomingData = "";
public int updateInterval = 4;
public int updateSlower = 0;
public bool useData = false;
// Use this for initialization
void Start () {
OpenConnection();
}
// Update is called once per frame
void Update (){
updateSlower ++;
if(portOpen && serialPort.IsOpen && updateSlower >= updateInterval){
RecieveInput();
updateSlower = 0;
}
}
public void OpenConnection(){
if(serialPort != null){
if( serialPort.IsOpen){
serialPort.Close();
Debug.Log("Closing port as it was already open");
}else{
serialPort.Open();
serialPort.ReadTimeout = 500;
portOpen = true;
if( errorHandling){
Debug.Log("Port open = " + serialPort.IsOpen);
}
}
}else{
if(serialPort.IsOpen){
Debug.Log("Port is already open");
}else{
Debug.Log("Port == Null");
}
}
}
void RecieveInput(){
try{
incomingData = serialPort.ReadLine();
//Debug.Log(serialPort.ReadLine());
if(errorHandling){
Debug.Log("data = " + incomingData);
}
useData = true;
}catch(Exception errorpiece){
if(useData){
Debug.Log("Error 1: " + errorpiece);
useData = false;
}
}
}
}
first of all, sorry for the wall of text, but i wont take anything out of context. Unity freezes whenever i try to run the “recieveInput” Method, i dont recieve any error message or something like that, and the only way for me to quit unity is to use the task manager.
now the Arduino script:
void setup() {
Serial.begin(9600);
}
void loop() {
Serial.flush();
Serial.print("I'm Alive");
delay(300);
}
To get the timeout error instead of a freeze i can change the timeout counter in the unity script to a value less than 300, if i put it above 300 the game freezes, this is becasue there’s a delay in the messages in the arduino script. I am completely lost here, and i have no idea why it happens, if i could at least get an error message when the game freezes, then i would have something to work with.
I’m looking forward to your replies.
Thanks in advance
- Kacer