- Home /
Lag issues with unity3d + Arduino (Xbee)
Hardware setup : Trigger -> Arduino -> Xbee ------------- Xbee -> PC (Serial port) -> Unity3d
The Xbee's are running in API mode, which means the data is encapsulated into a packet containing a start byte, checksum, the data, source address etc. This packet is set wirelessly to the other Xbee, which forwards it to the serial port.
Now I'm trying to get these packets into unity, retrieve the data and display it on the screen. Unfortunately, there is a HUGE lag between the time I change the trigger value, and the time it reflects on the screen.
I've observed the packet stream in a serial terminal (X-CTU) and the change reflects there immediately. Why is there such a lag within unity and how do I correct it? Someone help!
Unity Code
using UnityEngine;
using System;
using System.Collections;
using System.IO.Ports;
public class readSerial : MonoBehaviour {
SerialPort stream = new SerialPort("\\\\.\\COM15"); //Set the port (com15)
public GUIText txt;
public GameObject target;
const byte START_BYTE = 0x7E;
const int offset = 2;
byte read_bytes = 0;
byte MSB =0;
byte LSB =0;
byte[] comb = {0,0};
int counter = 0;
bool startCtr;
Int16 result;
void Start () {
//settings for the serial port copied from X-CTU
stream.BaudRate = 9600;
stream.Parity = Parity.None;
stream.DataBits = 8;
stream.StopBits = StopBits.Two;
stream.ReadTimeout = 3;
stream.Open();
StartCoroutine(ReadData());
}
// Update is called once per frame
void Update () {
txt.text = result.ToString();
if(read_bytes==161) //personal data identifier...A1
startCtr = true;
if(startCtr)
counter++;
if(counter == offset)
{
LSB = read_bytes;
}
if(counter == offset+1)
{
MSB = read_bytes;
comb[0] = LSB;
comb[1] = MSB;
result = BitConverter.ToInt16(comb, 0);
//txt.text = result.ToString();
counter = 0;
startCtr =false;
}
}
IEnumerator ReadData()
{
while(true)
{
read_bytes = (byte) stream.ReadByte();
yield return new WaitForEndOfFrame();
}
}
}
I tried putting the read bit in a separate thread, but that didn't help.
[CODE] and [/CODE] do nothing on this website. Watch the tutorial video on the right to see how code is formatted and plz fix up the question :)