1

So I currently have this for arduino.ino:

Serial.println(Variable1);

that does this in Unity:

string variable1 = stream.ReadLine();
float x = float.Parse(variable1);
transform.Rotate (0, -x/1000, 0);

My question is; How would I send 3 variables from the Arduino to Unity so I can put each value into the transform.Rotate function at once?

For example in pseudocode:

Arduino.ino
send(Variable1, Variable2, Variable3);

Unity
transform.Rotate(Variable1,Variable2,Variable3);

I hope this makes sense. Thank you.

2 Answers 2

1

On the Arduino side you use code such as:

void sendVector(float x, float y, float z) {
  Serial.print(x, 4);
  Serial.print(" ");
  Serial.print(y, 4);
  Serial.print(" ");
  Serial.println(z, 4);
}

Be aware of precision here. For floats Serial.print(x); is equivalent to Serial.print(x, 2); which gives you two decimal places. Serial.print(x, 4); gives you four decimal places. i.e.:

  • Serial.print(1.23456) => "1.23"
  • Serial.print(1.23456, 2) => "1.23"
  • Serial.print(1.23456, 4) => "1.2345"

REF: Serial.print()

Now, on the Unity side, you use C# code such as:

string[] elements = stream.ReadLine().Split(' ');
float x = float.Parse(elements[0]);
float y = float.Parse(elements[1]);
float z = float.Parse(elements[2]);
transform.Rotate(x, y, z);
Sign up to request clarification or add additional context in comments.

3 Comments

2 errors: --Assets/GyroNewNewNew.cs(31,47): error CS1503: Argument #1' cannot convert string' expression to type char[]'-- & --Assets/GyroNewNewNew.cs(31,41): error CS1502: The best overloaded method match for string.Split(params char[])' has some invalid arguments--
Apologies, I used " when I should have used ', I'll update the answer.
Yeah I noticed after I posted it! Thank you.
0

Arduino: Print all three variables with a separator between them, for example like this:

Serial.print(Variable1);
Serial.print("|"); //separator
Serial.print(Variable2);
Serial.print("|"); //separator
Serial.println(Variable3); //println instead of print on the last one

Unity: use the split function in C# to split the read string into an array:

string[] values = variable.Split('|');

The variable values should now be an array with three elements that can be parsed into floats.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.