Skip to content

Instantly share code, notes, and snippets.

@mellifluus
Last active February 2, 2021 11:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mellifluus/e48147a369ff5c0678bb7431b0d80a60 to your computer and use it in GitHub Desktop.
Save mellifluus/e48147a369ff5c0678bb7431b0d80a60 to your computer and use it in GitHub Desktop.
Unity snippet that finds out the COM port of a connected Arduino given its VID and PID.
using UnityEngine;
using System.Collections.Generic;
using System.IO.Ports;
using Microsoft.Win32;
public class DetectArduinoPort : MonoBehaviour
{
#pragma warning disable 649
[SerializeField]
private string VID, PID;
#pragma warning restore 649
public string AutodetectArduinoPort()
{
List<string> comPorts = new List<string>();
RegistryKey baseKey = Registry.LocalMachine.OpenSubKey("SYSTEM\\CurrentControlSet\\Enum\\USB\\VID_" + VID + "&PID_" + PID);
foreach (string subKey in baseKey.GetSubKeyNames())
{
RegistryKey paramKey = baseKey.OpenSubKey(subKey).OpenSubKey("Device Parameters");
if (paramKey != null)
{
string tmpPort = (string)paramKey.GetValue("PortName");
if(tmpPort != null)
comPorts.Add(tmpPort);
}
}
if (comPorts.Count > 0)
foreach (string s in SerialPort.GetPortNames())
if (comPorts.Contains(s))
return s;
return null;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment