[Python] Failing to connect to serial port using pyserial

Discussão em 'Python' iniciado por Stack, Fevereiro 21, 2025.

  1. Stack

    Stack Membro Participativo

    I'm trying to connect to a device using a serial port. I tried two ways - 1) pyserial in Python and 2) Putty. I managed to connect to the device and use it, using Putty. However, in Python I can only connect to the device (open the port) but I fail to send commands or read the port.

    Note that I'm using exactly the same settings in both my Python script (below) and Putty settings. But perhaps I'm missing something. How do I fix my script?

    My Python code (I'm using Windows 11):

    import serial
    import time


    def send_command_to_com_port(ser, command):
    try:
    # Send the command
    command_encoded = command.encode('ascii')
    ser.write(command_encoded)
    print(command_encoded)

    except serial.SerialException as e:
    print(f"Error communicating with the COM port: {e}")


    def read_from_com_port(ser):
    try:
    # Read response from the COM port
    response = ser.read_until("\n") # Read until a newline character is encountered
    if response:
    print(f"Response received: {response.decode('ascii').strip()}")
    else:
    print("No response received from the COM port.")

    except serial.SerialException as e:
    print(f"Error communicating with the COM port: {e}")


    # Specify the COM port and send the command
    com_port = "COM4"

    # Configure the serial connection
    ser = serial.Serial(
    port=com_port, # Replace with your COM port (e.g., 'COM3' on Windows or '/dev/ttyUSB0' on Linux)
    baudrate=115200, # Baud rate
    bytesize=serial.EIGHTBITS, # 8 data bits
    parity=serial.PARITY_NONE, # No parity bit
    stopbits=serial.STOPBITS_ONE, # One stop bit
    timeout=1 # Timeout in seconds
    )

    # Ensure the COM port is open
    print(f"Serial port opened: {ser.is_open}")

    # Send commands to the COM port
    send_command_to_com_port(ser, 'm0\n')
    time.sleep(2)
    read_from_com_port(ser)

    # Close the serial port
    ser.close()
    print("Serial connection closed.")


    The output I get using the code above is always:

    Serial port opened: True
    b'm0\\n'
    No response received from the COM port.
    Serial connection closed.

    Process finished with exit code 0


    Additional note: All instructions to the device must be ascii encoded and must end with a newline character '\n'.

    After sending the command 'm0' I should receive a confirmation as a string. But I get nothing.

    Continue reading...

Compartilhe esta Página