Hello, I'm trying to send data back and forth between Unity and my Arduino. The arduino code looks like this:
#include <LiquidCrystal.h>
LiquidCrystal lcd(2, 3, 4, 9, 10, 11, 12);
int incNo = 0;
void setup()
{
Serial.begin(9600);
lcd.begin(16, 2);
lcd.print("Unity Testing");
}
void loop()
{
GetInput();
SendOutput();
}
This is how I handle the recived input:
void GetInput()
{
if(Serial.available())
{
char ch = Serial.read();
if(ch >= '0' && ch <= '9')
{
incNo = (ch - '0');
lcd.setCursor(0, 1);
lcd.print(incNo);
}
}
}
This is how I send the recived input back. The problem with this is that the delay makes the game laggy.
But if I remove the delay Unity doesn't react to the input.
I can see that the Arduino recived my input from Unity on the LCD display when the delay is gone.
But it doesn't seem like it sends it back to Unity.
Is there any way around this?
void SendOutput()
{
delay(500);
Serial.write(incNo);
}
This is how I open the connection in Unity:
public class SerialPortConnector : MonoBehaviour
{
//the connection is static since there is only allowed this one instance.
public static SerialPort sp = new SerialPort("COM7", 9600); //POssibility of a form to change properties for connection and close it aswell. GUI.
// Use this for initialization
void Start()
{
OpenConnection();
}
public static void OpenConnection()
{
if (sp != null)
{
if (sp.IsOpen)
{
sp.Close();
Debug.Log("Port closed");
}
else
{
sp.Open();
Debug.Log("Port open");
}
}
else
{
if (sp.IsOpen)
{
Debug.Log("Port is already open");
}
else
{
Debug.Log("Port == null");
}
}
}
void OnApplicatioQuit()
{
sp.Close();
}
}
And this is how I send and recive data:
void Update ()
{
if (Input.GetKeyDown(KeyCode.A))
{
SerialPortConnector.sp.Write("1");
}
if (Input.GetKeyDown(KeyCode.D))
{
SerialPortConnector.sp.Write("2");
}
if (SerialPortConnector.sp.IsOpen)
{
myInt = SerialPortConnector.sp.ReadChar();
print(myInt);
}
}