- Home /
Can't auto find Arduino without crashing
I am trying to connect my arduino to my unity in such a way where if I take my arduino to another computer and download the unity game it will work. for that I will need to auto detect which port my arduino is on. I am trying to do that by adding a phrase to the start of the whole serial println string.
Every time I try to run this code it crashes unity. I can connect to the arduino by just putting in the right port, but I would really like to find the arduino on other computers without changing the code every time.
.
Unity code
using System.Collections; using
System.Collections.Generic; using
UnityEngine; using System.IO.Ports;
//Library to read our ardunio data
using System;
public class SquishyInput :
MonoBehaviour {
SerialPort SquishIn;
public bool FoundSquish = false;
public string DisplayLine;
public static bool SquishyIsRunning = false;
string[] NamePorts = SerialPort.GetPortNames();
void Start()
{
int Trys = 0;
Debug.LogError(NamePorts.Length.ToString());
Debug.LogError(NamePorts[0] + ", " + NamePorts[1]);
if (!SquishyIsRunning) {
while (Trys <= NamePorts.Length)
try
{
SquishIn = new SerialPort(NamePorts[Trys], 9600);
if (SquishIn != null)
SquishIn.Open();
SquishIn.ReadTimeout = 50;
FoundSquish = SquishIn.ReadLine().Contains("Bendele Tech: Squishy");
SquishyIsRunning = FoundSquish;
if (!FoundSquish) { SquishIn.Close(); }
if (FoundSquish) { Trys =100; }
}
catch { }
Trys++;
}
}
void Update()
{
if (SquishyIsRunning)
{
try
{
DisplayLine = SquishIn.ReadLine();
}
catch (System.Exception)
{
}
}
} }
Arduino Code.
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
}
void loop() {
// put your main code here, to run repeatedly:
String AIn0 = "," + String(analogRead(0));
String AIn1 = "," + String(analogRead(1));
String AIn2 = "," + String(analogRead(2));
String AIn3 = "," + String(analogRead(3));
String AIn4 = "," + String(analogRead(4));
String AIn5 = "," + String(analogRead(5));
//Serial.flush();
Serial.println("Bendele Tech: Squishy" + AIn0 + AIn1 + AIn2 + AIn3 + AIn4 + AIn5);
delay(50);
}
Comment
Your answer
![](https://koobas.hobune.stream/wayback/20220612150608im_/https://answers.unity.com/themes/thub/images/avi.jpg)