[Python] Function "read_holding_registers" of pymodbus

Discussão em 'Python' iniciado por Stack, Julho 11, 2025.

  1. Stack

    Stack Membro Participativo

    I try read modbus RTU from serial device. This is example of simple reading from port "COM7". This port is wrong, from some bluetooth device. I can not determine, that it port is wrong. Calling of "read_holding_registers" does not ruturn any value or exception. Prorgram is freeze on calling that function. What can I do? P.S. With write port of RS-485 adpter it works fine, or some another ports of PC.

    from pymodbus.client import ModbusSerialClient
    from pymodbus.exceptions import ModbusException
    import logging

    # Configure logging for debugging
    logging.basicConfig(level=logging.INFO)
    logger = logging.getLogger(__name__)

    def read_holding_registers(port, slave_id, start_address, count):
    """
    Reads Holding Registers from a Modbus device.

    Args:
    port (str): COM port (e.g., 'COM7' or '/dev/ttyUSB0' on Linux).
    slave_id (int): Modbus Slave ID (default = 1).
    start_address (int): Starting register address (0x0000).
    count (int): Number of registers to read.

    Returns:
    list[int] | None: List of register values or None if an error occurs.
    """
    # Initialize Modbus RTU client
    client = ModbusSerialClient(

    port=port, # Serial port (e.g., 'COM7')
    baudrate=9600, # Baud rate (adjust if needed)
    stopbits=1, # Stop bits (usually 1 or 2)
    bytesize=8, # Data bits (usually 8)
    parity='N', # Parity ('N' = None, 'E' = Even, 'O' = Odd)
    timeout=2 # Response timeout (seconds)
    )

    try:
    # Connect to the device
    if not client.connect():
    logger.error("Failed to connect to the device.")
    return None

    # Read Holding Registers (Function Code 0x03)
    response = client.read_holding_registers(
    address=start_address,
    count=count,
    slave=slave_id
    )

    # Check for Modbus errors
    if response.isError():
    logger.error(f"Modbus Error: {response}")
    return None

    logger.info(f"Successfully read {len(response.registers)} registers.")
    return response.registers

    except ModbusException as e:
    logger.error(f"Modbus Exception: {e}")
    return None
    except Exception as e:
    logger.error(f"Unexpected Error: {e}")
    return None
    finally:
    client.close() # Ensure the connection is closed

    if __name__ == "__main__":
    # Example usage
    PORT = 'COM7' # Serial port (adjust as needed)
    SLAVE_ID = 1 # Slave ID (check your device manual)
    START_ADDR = 0 # First register address (0x0000)
    REG_COUNT = 10 # Number of registers to read

    print(f"Reading {REG_COUNT} Holding Registers starting from address {START_ADDR}...")
    registers = read_holding_registers(PORT, SLAVE_ID, START_ADDR, REG_COUNT)

    if registers is not None:
    # Print register values in decimal and hex
    for i, reg in enumerate(registers):
    print(f"Register {START_ADDR + i}: {reg} (0x{reg:04X})")
    else:
    print("Failed to read registers. Check connection and parameters.")



    I tried to catch exception, it did not work

    Continue reading...

Compartilhe esta Página