Serial communication slows down FPS

Hi everyone, I have a very simple project, I made a serial connection with an arduino board. The serial communication is done through a bluetooth connected to the arduino. All the arduino does is collecting data from an accelerometer and sends it through bluetooth. In unity I receive the data and print it in the Debug console.
My problem is that, it slows down Unity to almost 1fps. I really need a workaround for this, could anyone help me?

Here is the code:

`
using UnityEngine;

using System.Collections;

using System.IO.Ports;

using System.Threading;

public class SerialPortTest : MonoBehaviour

{

public static SerialPort sp = new SerialPort(“COM4”, 9600, Parity.None, 8, StopBits.One);

public static string strIn;

public static int[] val = new int[2];

// Use this for initialization
void Start () 
{
OpenConnection();
}

void OnGUI() 
{
     strIn = sp.ReadLine();
		strIn = strIn.Trim();
		string[] temp = strIn.Split(',');
		val[0] = System.Convert.ToInt32(temp[0]); 
		val[1] = System.Convert.ToInt32(temp[1]);
		print(val[0] + " " + val[1]);
}

public void OpenConnection() 
{
	if (sp != null) 
	{
		if (sp.IsOpen) 
		{
			sp.Close();
			message = "Closing port, because it was already open!";
		}
		else 
		{
			sp.Open();  // opens the connection
			sp.ReadTimeout = 50;  // sets the timeout value before reporting error
			message = "Port Opened!";
		}
	}
	else 
	{
		if (sp.IsOpen)
		{
			print("Port is already open");
		}
		else 
		{
			print("Port == null");
		}
	}
}

void OnApplicationQuit() 
{
	sp.Close();
}

`

I would guess that reading the port in OnGUI would be the hold up. Try reading in Update, and in a non-blocking way (read whatever is there and assemble a buffer, looking for end-of-line yourself, rather than using readline). Or use a coroutine.

As @DaveA states, the problem might be where you check the input.

I also believe the sp.Readline() is the bottleneck here. I suspect it to stall/block until data is ready.

But if you need to output it in the OnGUI then keep the result in a shared string in your class.

GUI is called twice each frame and Update can be called more than once per frame.

So you should consider to make your reader as a seperate module you can spawn with threading or perhaps use Yield function on it.

Omg, DaveA, thank you for the response, it was so simple I can’t believe it, I tried a lot of different other possibilities, using threads and Coroutines, but none of those helped, but this one is perfect, don’t know why I didn’t think of it. It works very nice, still it drops the fps from 60 to 30, but now it at least works as expected. I’ll try now to use Readbyte() instead of Readline().
Thanks a lot again :wink:
Cheers!