Hello everyone, I want to start using Unity (game engine) with Arduino. In unity I have 2 buttons, each one sends a different message to the arduino, the messages are "1" and "2". Arduino receives the message and decides to turn on or off the LED on the 13th pin. First, look at the codes.
Here is the Unity C# code:
using UnityEngine;
using System.Collections;
using System.IO.Ports;
public class SerialPortTest : MonoBehaviour
{
public static SerialPort sp = new SerialPort("COM3", 9600, Parity.None, 8, StopBits.One);
public int count = 0;
public string message, message1;
public int message2;
void Start ()
{
OpenConnection();
}
void OnGUI()
{
GUI.Label(new Rect(230, 60, 500, 20), "" + message1 + " Received " + message2);
GUI.Label(new Rect(120, 10, 500, 30), "Status: "+message);
if (GUI.Button(new Rect(10, 60, 200, 30), "Light on"))
{
if (sp.IsOpen)
{
message1 = "Sent 1";
sp.Write("1");
message2 = sp.ReadByte();
}
}
if (GUI.Button(new Rect(10, 150, 200, 30), "Light off"))
{
if (sp.IsOpen)
{
message1 = "Sent 2";
sp.Write("2");
message2 = sp.ReadByte();
}
}
}
void Update ()
{
}
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 = 100; // 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();
}
}
And here is the Arduino code:
void setup() {
Serial.begin(9600);
pinMode(13, OUTPUT);
}
void loop()
{
if (Serial.available())
{
if(Serial.read() == 50){
Serial.write(30);
digitalWrite(13, LOW);
}
else if(Serial.read() == 49){
Serial.write(20);
digitalWrite(13, HIGH);
}
}
}
The problem is that I receive the answer in unity only when I send the message "2" to Arduino. It's really strange, if I switch the "if"s with places in the Arduino Code then it works only when I send the "1" message, it seems Arduino doesn't go through the whole loop but just through the first "if".
Could anyone help me with this?
Thanks