[Python] Modbus TCP with Python

Discussão em 'Python' iniciado por Stack, Abril 12, 2025.

  1. Stack

    Stack Membro Participativo

    I am trying to communicate with Modbus via TCP. I want to use this type of code without a library.

    The code is run like this :

    sudo python3 modbus_master.py


    When I run the program with this code then I see my Modbus connection defined in Wireshark. I am also using slave Modbus programs (more than one) but there is no connection with my master.

    What am I doing wrong in the following code?

    #!/usr/bin/python3
    # This is client.py file

    import socket
    import struct
    import time

    # Create a TCP/IP socket
    TCP_IP = '192.168.0.107'
    TCP_PORT = 502
    BUFFER_SIZE = 39
    sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
    sock.connect((TCP_IP, TCP_PORT))

    try:

    unitId = 16
    functionCode = 5
    print("\n,Switching plug on")
    coilId = 1
    req = struct.pack('12B', 0x00, 0x00, 0x00, 0x00, 0x00, 0x06, int(unitId), int(functionCode), 0x00, int(coilId),
    0xff,
    0x00)
    sock.send(req)
    print("TX: (%s)" % req)


    time.sleep(2)

    finally:
    print('\nCLOSING SOCKET')
    sock.close()

    Continue reading...

Compartilhe esta Página