Is there a way to find out what's connected to each port? #799
-
I'd like my program to behave differently depending on what's connected to the ports. This works:
but I don't suppose trapping exceptions is the best way to do it. I see there's a method for EV3, #152, so maybe something similar works with PU hubs? |
Beta Was this translation helpful? Give feedback.
Replies: 3 comments 1 reply
-
Try this example: https://docs.pybricks.com/en/latest/iodevices/pupdevice.html#detecting-devices |
Beta Was this translation helpful? Give feedback.
-
Thank you. So exceptions of one sort or another are the best/only way to do it... |
Beta Was this translation helpful? Give feedback.
-
Here's a variant that could help you keep your main script fairly clean. Put this in a file called from pybricks.iodevices import PUPDevice
from pybricks.parameters import Port
from uerrno import ENODEV
def get_device_id(port):
"""Get device ID, or 0 if nothing is attached."""
try:
device = PUPDevice(port)
return device.info()["id"]
except OSError as ex:
if ex.args[0] == ENODEV:
return 0
else:
raise Then, in your main script, you can do: from device_handler import get_device_id
from pybricks.parameters import Port
# Get device ID
id = get_device_id(Port.A)
print(id) |
Beta Was this translation helpful? Give feedback.
Try this example: https://docs.pybricks.com/en/latest/iodevices/pupdevice.html#detecting-devices