Created
October 14, 2023 23:24
-
-
Save kevinlinxc/b452d7685f082006ea7f9c61722f1380 to your computer and use it in GitHub Desktop.
Arduino Port Detector Utility
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
""" | |
This simple helper script auto-detects the Arduino port. | |
Saves time because you don't need to check the Arduino IDE/device manager to get the port number each time. | |
""" | |
import serial.tools.list_ports | |
def get_port(): | |
""" | |
Get the port name of a connected Arduino if one is connected. | |
Iterates over the serial ports and looks for Arduino or "USB-SERIAL" in their names to auto connect to a port. | |
:return: a string that is the name of the connected Arduin's port, or a RuntimeError if none found | |
""" | |
ports = list(serial.tools.list_ports.comports()) | |
if len(ports) == 0: | |
error = "No COM ports detected, is the Arduino plugged in?" | |
print(error) | |
raise RuntimeError(error) | |
print("#####\nDetected the following COM ports: ") | |
probable_port = "" | |
for p in ports: | |
print(p.description) | |
if "Arduino" in p.description or "USB-SERIAL" in p.description: | |
# you can change these if statements to detect the knockoff Arduinos. | |
probable_port = ( | |
p.name | |
) # don't return immediately so all ports are printed out | |
if not probable_port: | |
error = "COM ports were detected, but none were detected to be Arduino" | |
print(error) | |
raise RuntimeError(error) | |
print("#####") | |
print(f"Choosing port {probable_port}") | |
return probable_port | |
if __name__ == "__main__": | |
print(get_port()) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment