- Home /
Unity to Arduino (write serial) Framerate fall
Hi !
I send bytes to my arduino (with an interval ) via the serial with unity. All is fine except after some seconds the framerate fall under 5 fps
I don't know why here I use the invokerepeating method, I have also use an time interval in the update but the result is the same the framerate fall...
I am interested in a solution
Thanks in advance !
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.IO;
public class Com : MonoBehaviour {
public bool outputToSerial=true;
public byte m1_1=0;
public byte m1_2=0;
public byte m2_1=0;
public byte m2_2=0;
SerialPort sp = new SerialPort("COM6", 9600);
void Start () {
sp.Open();
InvokeRepeating("RepeatingSend", 1, 0.2f);
}
void RepeatingSend () {
SendToSerial((byte) m1_1,(byte) m1_2,(byte) m2_1,(byte) m2_2);
}
void SendToSerial(params byte[] cmd)
{
if (outputToSerial)
{
if (sp.IsOpen){
try {
sp.Write( cmd, 0, cmd.Length );
}
catch (System.Exception ex)
{
Debug.LogWarning(ex);
}
}
}
}
}
Hi,
Did you find an answer?
I am reading data via USB serial from my arduino, and it makes the FPS drop as well. In fact if the arduino sends data packages too fast, like under every 100ms, unity will be extremely slow.
I guess there might be a way to synchronise both based on the targeted framerate?
Answer by canert · May 12, 2016 at 01:01 PM
I solve this problem with multi-threading structure. while unity works on the graphic and other things, you can create your own thread in the operating system. this helps you for using other cores of the processor and your fps probably will increase.
The unity works in Main thread
//in awake or start
MyThreadClass thread;
thread.StartThread(); // your thread started here and the unity continue to process other things.
...
and serial communication processes are in the other thread class.
private Thread thread;
public bool StartThread()
{
// initializing things // port open.
if (thread == null)
{
thread = new Thread(ThreadJob);
thread.IsBackground = true;
thread.Start();
}
}
private void ThreadJob()
{
while(true){
// write things to port
// listen port
}
}
you can search concurrent programming for more things , I have also new in this field :D
I hope I could help you
You can search semaphore,mutex,lock and monitor keywords for communication between unity and your thread