Arduino to Unity communication

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 () {
	// Update is called once per frame
	void Update (){
		updateSlower ++;
		if(portOpen && serialPort.IsOpen && updateSlower >= updateInterval){
			updateSlower = 0;
	public void OpenConnection(){
		if(serialPort != null){
			if( serialPort.IsOpen){
				Debug.Log("Closing port as it was already open");
				serialPort.ReadTimeout = 500;
				portOpen = true;
				if( errorHandling){
					Debug.Log("Port open = " + serialPort.IsOpen);
				Debug.Log("Port is already open");
				Debug.Log("Port == Null");
	void RecieveInput(){
			incomingData = serialPort.ReadLine();
				Debug.Log("data = " + incomingData);
			useData = true;
		}catch(Exception errorpiece){
				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() {  

void loop() {
  Serial.print("I'm Alive");

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

If I’m not mistaken, ReadLine will block (not return) until it finds an EOL, which may or may not happen quickly. Use a non-blocking read instead and build a circular buffer, looking for EOL yourself. And/or put an eol in your outgoing string, eg: "I’m alive
" (but also try \r,
\r) Maybe print is supposed to do it for you, I never trust them.

To send an EOL in Arduino you have to use println(“whatevertext”);