Search Unity

  1. Welcome to the Unity Forums! Please take the time to read our Code of Conduct to familiarize yourself with the forum rules and how to post constructively.
  2. Dismiss Notice

Latency between Arduino & Unity caused by readBytesUntil

Discussion in 'Scripting' started by j_campbell, Mar 3, 2015.

  1. j_campbell

    j_campbell

    Joined:
    Dec 8, 2014
    Posts:
    33
    Hi - I have created a game with the unity game engine and have two way serial communication with an arduino. I can send data to Unity using Serial.println without any problem. However when I try and send a letter to Arduino from Unity I am getting incredible latency. The latency is being caused by the following code. It slows down the entire game and also slows down the data being sent to unity from Arduino.

    {
    int lf = 10;
    Serial.readBytesUntil(lf, myCol, 1);
    if(strcmp(myCol,"A")==0){
    digitalWrite(StimPin, HIGH);
    }

    Can anyone recommend a workaround or point out what is causing the latency ?
    Thanks
    Joey
     
  2. lordofduct

    lordofduct

    Joined:
    Oct 3, 2011
    Posts:
    8,377
    not sure what library you're using to read and write bytes. The method names you have there are rather generic, and you don't identify at all what they are.

    But, most libraries block while reading and writing bytes. And there is always latency in doing so.

    This means that while you read and/or write, if you do so on the main thread, the application with freeze until complete.

    It's best to do these sorts of thing asynchronously.
     
  3. j_campbell

    j_campbell

    Joined:
    Dec 8, 2014
    Posts:
    33
    Thanks for getting back. Can you suggest how I would go about not reading/writing to the serial port simultaneously ?
    Would I have to open the port, read from it, close the port, open the port, write to it ?

    This is the full script:
    using UnityEngine;
    using System.Collections;
    using System.IO;
    using System.IO.Ports;
    using System.Threading;

    public class JoeysInputStick : MonoBehaviour {
    public static SerialPort sp = new SerialPort("/dev/cu.usbmodem1411", 9600);
    public static int flex = 0;
    private int flexValue;

    void Start ()
    {}

    void Update () {
    if (!sp.IsOpen)
    sp.Open ();
    flex = (int.Parse (sp.ReadLine()));
    flexValue = flex;
    }

    void OnGUI()
    {
    GUI.Label(new Rect (55, 575, 100, 20),"Flex Value: " + flexValue.ToString("0"));
    }

    public static void SendTensOn()
    {
    Debug.Log("Tens turned on");
    sp.Write ("A");
    }

    }