Last active
February 2, 2021 11:22
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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