- Home /
Question by
saml_baker · Apr 02, 2018 at 03:12 AM ·
unity 5rotationarduinoserialportserial.io.port
Need Help Connecting Arduino to Unity
Hi. I am trying to make a glove with my arduino uno in which I am able to connect a potentiometer to each finger import the serial data into Unity to control a character. In my arduino sketch it is pretty simple. It converts the analog input of the pot, then converts it into degrees (0 - 179) where it is put into the serial monitor. In Unity I made a script that looks like this.
using UnityEngine;
using System.Collections;
using System.IO.Ports;
using System;
using System.Linq;
public class ArduinoConnector : MonoBehaviour
{
SerialPort sp;
string[] stringDelimiters = new string[] { ":", "R", }; //Items we want to ignore in strings.
public Transform target; //The item we want to affect with our accelerometer
void Start()
{
sp = new SerialPort("COM5", 9600, Parity.None, 8, StopBits.One); //Replace "COM4" with whatever port your Arduino is on.
sp.DtrEnable = false; //Prevent the Arduino from rebooting once we connect to it.
//A 10 uF cap across RST and GND will prevent this. Remove cap when programming.
sp.ReadTimeout = 1; //Shortest possible read time out.
sp.WriteTimeout = 1; //Shortest possible write time out.
sp.Open();
if (sp.IsOpen)
{
sp.Write("Hello World");
Debug.Log("Connection Successful!");
}
else
Debug.LogError("Serial port: " + sp.PortName + " is unavailable");
}
void Update()
{
string cmd = CheckForRecievedData();
float position = Single.Parse(cmd);
target.transform.rotation = Quaternion.Slerp(target.transform.rotation, Quaternion.Euler(target.transform.rotation.x, target.transform.rotation.y, position + 90f), Time.deltaTime * 2f);
if (Input.GetKeyDown(KeyCode.Escape) && sp.IsOpen)
sp.Close();
}
public string CheckForRecievedData()
{
try //Sometimes malformed serial commands come through. We can ignore these with a try/catch.
{
string inData = sp.ReadLine();
int inSize = inData.Count();
if (inSize > 0)
{
Debug.Log("ARDUINO->|| " + inData + " ||MSG SIZE:" + inSize.ToString());
}
//Got the data. Flush the in-buffer to speed reads up.
inSize = 0;
sp.BaseStream.Flush();
sp.DiscardInBuffer();
return inData;
}
catch { return string.Empty; }
}
}
My problem is that when I run this it takes in the data in the beginning and rotates the object but then does not update for the rest of the time almost as if it is in the start function even though I put it in update. I do not know what the problem is but if anyone has any experience with this I would really appreciate some help. Thanks!
Comment