- Home /
Help with Unity communicating with Arduino (serial port communication)
Hi everyone. Please bear with me as I am fairly new to both Unity and Arduino so I will most likely butcher the typical terminology of most things. I am working on a project where I am using the encoder counts on a motor to control the position of a drillbit model within Unity. The encoder position is written to the Arduino as a float with a baud rate of 115200. I have it writing to COM Port 4 which is then being read by Unity. I am encountering a problem where, quite frequently, the strings being read by Unity do not match what is being written by Arduino. For instance, say Arduino is writing 0.0152, the console in Unity will say 00152, or 0.152. Either it will forget a decimal or a digit entirely and will cause the system to glitch as the incorrect value is being read in Unity. I have noticed that when I run the program on my desktop computer which has a strong processor and graphics card, I have this problem far less compared to when I run the program on my laptop, which is much less powerful. This makes me think it is just a processing issue but I am not entirely sure. If anyone has any suggestions to stop Unity from incorrectly reading the Arduino values, that would be amazing. If there is any additional information that you need to help you better understand the problem, please don't hesitate to ask.
Here is the Unity code:
using System.Collections; using System.Collections.Generic; using UnityEngine; using System.IO.Ports;
public class ArduinoCommunication : MonoBehaviour { // Data Variables public float piecePosition; public float pieceRotationSpeed; public float clearedInput; public float betweenInput; public float cloggedInput;
// Data Communication
private SerialPort stream;
private string data;
private bool dataFound = false;
private List<float> parsedData;
void Start()
{
stream = new SerialPort(PlayerPrefs.GetString("COM"), 115200);
stream.Open();
stream.ReadTimeout = 101;
Debug.Log(PlayerPrefs.GetString("COM"));
}
void Update()
{
try
{
data = stream.ReadExisting();
parsedData = ParseFile(data);
SetDataVariables();
dataFound = true;
Debug.Log("Data found.");
}
catch (System.Exception)
{
dataFound = false;
Debug.Log("No data found.");
}
}
private List<float> ParseFile(string text)
{
char[] separators = {','};
string[] strValues = text.Split(separators);
List<float> intValues = new List<float>();
foreach (string str in strValues)
{
float val = 0;
if (float.TryParse(str, out val))
intValues.Add(val);
}
return intValues;
}
private void SetDataVariables()
{
piecePosition = parsedData[0];
pieceRotationSpeed = parsedData[1];
clearedInput = parsedData[2];
betweenInput = parsedData[3];
cloggedInput = parsedData[4];
}
}
Also here is a photo from Unity's console showing the incorrect value being produced.