[Python] pySerial wait for "#" character to print output from USB serial device

Discussão em 'Python' iniciado por Stack, Maio 4, 2025.

  1. Stack

    Stack Membro Participativo

    I'm writing a python script that connects to a USB serial device. Whenever a command is sent and executed, the PIC returns with a hashtag. Ie. "Command executed successfully. \n# "

    I'd like my python script to wait for the hashtag before outputting the data. How can I do this? Here's what I have. It doesn't seem to actually print the text received from the PIC. Any help is appreciated

    if port.isOpen():
    try:
    for x in range(0,100):
    time.sleep(0.05)
    port.write("command 1" + "\r\n")
    numLines = 0
    // wait for "#" to print output
    while True:
    response = port.readline()
    if "#" in response:
    print(response)
    numLines = numLines + 1
    if(numLines >= 1):
    break

    time.sleep(0.05)
    port.write("command 2" + "\r\n")
    numLines = 0
    // wait for "#" to print output
    while True:
    response = port.readline()
    if "#" in response:
    print(response)
    numLines = numLines + 1
    if(numLines >= 1):
    break

    time.sleep(0.05)
    port.write("command 3" + "\r\n")
    numLines = 0
    // wait for "#" to print output
    while True:
    response = port.readline()
    if "#" in response:
    print(response)
    numLines = numLines + 1
    if(numLines >= 1):
    break

    except Exception, e1:
    print("An error occured: " + str(e1))
    port.close()

    Continue reading...

Compartilhe esta Página