Hello, I`m trying to send a string data from unity to Arduino Uno
The object in Unity rotates and the servo motor also rotates according to the angle of the Unity object. The angle of the Unity object is transmitted to Arduino through serial communication. However, when running Unity and Arduino, Unity displays “Port Open!”, but the servo motor does not rotate. Can you help me with this part?
Below is my code. The first one is unity 3D scripts and the second one is Arduino code.
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System.Threading;
public class SerialCommunication : MonoBehaviour {
public static SerialPort arduino = new SerialPort("COM6", 9600);
public GameObject Object;
float angle;
void Start () {
OpenConnection();
}
void Update () {
angle = Object.transform.eulerAngles.y;
sendAngle(angle.ToString());
}
public void OpenConnection(){
if(arduino != null){
if(arduino.IsOpen){
arduino.Close();
print("Closing port, because it was already open!");
}
else{
arduino.Open();
arduino.ReadTimeout = 16;
print("Port Opend!");
}
}
else{
if(arduino.IsOpen){
print("Port is arleady opened");
}
else{
print("Port == null");
}
}
}
public void sendAngle(string data){
arduino.Write(data);
}
}
#include<Servo.h>
#define Servopin 7
Servo servo;
float angle = 90.0;
void setup() {
servo.attach(Servopin);
servo.write(angle);
Serial.begin(9600);
}
void loop() {
if(Serial.available()){
String serialData = Serial.readString();
angle = serialData.toFloat();
servo.write(angle);
delay(100);
}
}
Thank You!