Any way to delay opening serial port monitor?

This wasn’t working for me.
I updated this to work for me for teensy4.1

I haven’t tested with multiple devices yet so I don’t know if that part works, but this does make Upload and Monitor work to wait for the serial port to connect for me when I only have one teensy 4.1 connected.

Hope this helps:


# see: https://community.platformio.org/t/builder-get-monitor-port-value-from-ini/20425/3
# see: https://github.com/platformio/platformio-core/issues/3742#issuecomment-1003454439

Import("env")

from platformio import exception, fs, util

def get_monitor_port():
    platform = env.PioPlatform()
    project_options = env.GetProjectOptions()
    kwargs = {}
    monitor_port = ""
    if "monitor_port" in project_options:
        monitor_port = project_options["monitor_port"]
    else:
        ports = util.get_serial_ports(filter_hwid=True)
        if len(ports) == 1:
            kwargs["port"] = ports[0]["port"]
            monitor_port = kwargs["port"]
        elif "platform" in project_options and "board" in project_options:
            board_hwids = env.BoardConfig().get("build.hwids", [])
            for item in ports:
                for hwid in board_hwids:
                    hwid_str = ("%s:%s" % (hwid, hwid)).replace("0x", "")
                    if hwid_str in item["hwid"]:
                        kwargs["port"] = item["port"]
                        break
                if kwargs["port"]:
                    break
            monitor_port = kwargs["port"]

    # print("Final monitor port: %s" % monitor_port)
    return monitor_port

def wait_for_monitor_port(source, target, env):
    import time
    startTime = time.time()
    port = get_monitor_port()
    if port is None:
        # print("Can't find port yet...")
        pass
    if port == "":
        # print("Can't find port yet...")
        pass

    print(f"Waiting for monitor port {port}...")
    import serial
    while True:
        time.sleep(0.25)
        port = get_monitor_port()
        if port is None:
            # print("port is None")
            print(".", end="")
            continue
        if port == "":
            # print('port is "" ')
            print(".", end="")
            continue
        try:
            # print(f"Found port: {port}\t\tTrying to open")
            print(".", end="")
            serial.Serial(port)
            totalTime = time.time()-startTime
            print(f"\nPort {port} opened. Took {totalTime:.2f} seconds")
            break
        except Exception as e:
            # print(f"Exception occurred: {e}")
            continue

env.AddPostAction("upload", wait_for_monitor_port)