I am trying to move servos with a VR headset, I am using the Unreak 4 Arduino Plugin, but that is not the problem. I send the rotation Y and Z from the headset, convert them to int and then send them together as an int separated by commas. Here's what it does: It gets the rotation Z, it converts it to int, then it converts it to String, I add a comma at the end of the String, then I add the rotation Y after the comma, and it returns me: "rotationZ","rotationY" (the values between " are the numbers sent by Unreal to arduino), these results may come in negative or positive value.
Then inside arduino I have this code:
#include <Servo.h>
#include <SoftwareSerial.h>
Servo servo1;
Servo servo2; // Crea un Objeto servo
int angle = 10;
int posicion = 10; // Variable de la posicion del servo
String user_input1;
int r;
int g;
void setup()
{
Serial.begin(9600);
servo1.attach(2); // Selecionamos el pin 2 como el pin de control para el servo
servo2.attach(3); // Selecionamos el pin 2 como el pin de control para el servo
servo1.write(0);
servo2.write(0);
Serial.setTimeout(5);
}
void loop()
{
if (Serial.available() > 0)
{
String firstValue = Serial.readStringUntil(',');
// String first = Serial.readString(); //next character is comma, so skip it using this
String secondValue = Serial.readStringUntil(',');
// String second = Serial.readString();
r = firstValue.toInt();
g = secondValue.toInt();
}
if (r < 0)
{
r = r * -1;
}
if (g < 0)
{
g = g * -1;
}
Serial.println(r);
Serial.println(g);
servo1.write(r);
servo2.write(g);
}
As you can see, it gets the numbers between the commas and then it converts them to int, and then it applies to the servos which are in pins number 2 and 3 (yes, everything is plugged in correctly), which it should then move them acordingly the position of the VR headset, I've also tried to make them always receive positive results but still doesn't work. I have searched over the internet on how to separate a string divided by commas and I still don't know if it's correctly done.
EDIT: I also tried to input the numbers in the console manually, and it gets them right and moves the servos but it still doesn't work with the VR. I also added Serial.setTimeout(5) to try if it works that way.
Thanks in advance for reading this bunch'o text about my problem.