- Home /
Unity crashes when connecting to a serial port
Hi, I wanted to create a VR game with a custom made controller made using Arduino.
I want to ready my values from my Arduino board by printing them on the serial port, the only problem is that when unity connects correctly to the port it just won't respond, I checked my task manager and it utilises 0% of my CPU.
I've tried to reduce my code to be as barebones as possible to avoid any errors but it seems like the crash shows up only when a correct connection is established between the COM port and Unity since my game will run just fine and display the appropriate error when the port is not available or I don't open the port.
It also appears that a connection has indeed started since when I try to open the Serial Monitor from the Arduino IDE it says that the port is busy.
Here's my Unity code:
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System.IO.Ports;
public class ArduinoCommunication : MonoBehaviour
{
SerialPort stream = new SerialPort("COM1", 9600);
public string RecevedString;
public string[] Donnee;
public string[] DonneRecu;
// Start is called before the first frame update
void Start()
{
stream.Open();
}
// Update is called once per frame
void Update()
{
RecevedString = stream.ReadLine();
//stream.BaseStream.Flush();
/*string[] Donnee = RecevedString.Split(',');
if (Donnee[0] != "" && Donnee[1] != "" && Donnee[2] != "" && Donnee[3] != "" && Donnee[4] != "" && Donnee[5] != "" && Donnee[6] != "" && Donnee[7] != "")
{
DonneRecu[0] = Donnee[0];
DonneRecu[1] = Donnee[1];
DonneRecu[2] = Donnee[2];
DonneRecu[3] = Donnee[3];
DonneRecu[4] = Donnee[4];
DonneRecu[5] = Donnee[5];
DonneRecu[6] = Donnee[6];
DonneRecu[7] = Donnee[7];
stream.BaseStream.Flush();
}
*/
}
}
If you think you know how I can solve my problem make sure to respond, please.
Have a nice day!
Hash
I don't really know the final solution, but it might have something to do with Unity's single threaded nature.. You might want to check if the serial connection blocks the main thread, if you can release it or if you can run the connection on another thread.
It was that!
Idk why it did block the main thread tho, but I followed this man's way of doing it and it works fine now:
https://answers.unity.com/questions/1696938/arduino-serial-delegate-help.html
I can even exchange data in both directions without any heckups now!
You could now post your code and accept your own answer, to help other ppl find it quicker ;)
Your answer
Follow this Question
Related Questions
Sending Data From Unity To Arduino 0 Answers
Need Help Connecting Arduino to Unity 0 Answers
Connect Android and Arduino with OTG Cable 1 Answer
SerialPort doesn't work on Xcode simulator 0 Answers
Two Arduino Boards for Same project 0 Answers