Pymodbus library communication delay
07:31 02 Mar 2026

I have the following example code. This code updates the frequency setting of the motor currently in use and gives it a forward movement command. I also add a specific waiting time in seconds while performing these operations.

from pymodbus.client import ModbusSerialClient
import time

PORT = "/dev/ttyAMA2"
BAUDRATE = 19200
PARITY = 'N'
STOPBITS = 1
SLAVE_ID = 1

REG_OP_CMD = 8
REG_FREQ_RAM = 13
REG_RESET = 1

def connect():
    client = ModbusSerialClient(
        port=PORT,
        baudrate=BAUDRATE,
        parity=PARITY,
        stopbits=STOPBITS,
        timeout=1
    )
    if client.connect():
        print("Connection successful.")
        result = client.read_holding_registers(address=8, count=1, slave=1)
        print("Result: ", result)
        return client
    else:
        print("Connection failed!")
        return None

def forward(client):
    return client.write_register(REG_OP_CMD, 2, slave=SLAVE_ID)

def stop_motor(client):
    return client.write_register(REG_OP_CMD, 1, slave=SLAVE_ID)

def set_freq(client, hz):
    raw = int(hz * 100)
    return client.write_register(REG_FREQ_RAM, raw, slave=SLAVE_ID)

def main():
    client = connect()
    if not client:
        return

    try:
        print("Frequency set to 20 Hz")
        set_freq(client, 20)
        time.sleep(2)

        print("Moving Forward...")
        forward(client)
        time.sleep(3)

        print("3 seconds passed. Motor stopped.")
        stop_motor(client)
        time.sleep(2)

        print("TEST COMPLETED SUCCESSFULLY...")

    finally:
        client.close()
        print("Port closed.")

if __name__ == "__main__":
    main()

When I run this code continuously on the system, after a certain period of time, the stop command to the motor is delayed. (This situation is not very stable. For example, the code ran without problems 5 times, but on the 6th run, the stop command was delayed. This could also happen if it runs without problems 10 times and the stop command is delayed on the 11th run.)

I'm curious about the answers to two questions here:

1. Is the problem of the commands not functioning after a certain period of time due to the continuous rerun of this script code? If so, what can I do?

2. Will I experience this problem in a large project where, after establishing a connection only once, the motor is repeatedly prompted to "go forward and wait 3 seconds"?

Version
---------
pymodbus : 3.8.6

python usb communication pymodbus