Quantcast
Channel: Raspberry Pi Forums
Viewing all articles
Browse latest Browse all 1234

Python • Re: Connecting RS485 via Modbus to Mitsubishi

$
0
0
I FINALLY FIXED, i will provide same example. I hope this will be helpfull for everyone that have any issue connecting Mitsubishi and Raspberry. Maybe it will help me again!
These are the connection, please don't refear to the color (even if this is a standard RJ-45 color set), but the number of the pin (1 - 8):
schema.png
Connections:
pin 3 and 5 of the RJ-45 goes to A
pin 4, 6 and 8 goes to B

Simple code to write and read to the Mitsubishi using the pymodbus library.
Reading:

Code:

import timefrom pymodbus.client import ModbusSerialClientdef read_modbus_registers_via_serial(port, baudrate, parity, stopbits, unit_id, start_address, count):    # Create a Modbus Serial client with the specified parameters    client = ModbusSerialClient(        method='rtu',        port=port,        baudrate=baudrate,        parity=parity,        stopbits=stopbits,        bytesize=8,        timeout=1,        rtscts=True    )        try:        # Connect to the client        if not client.connect():            print("Unable to connect to the Modbus server via serial port")            return None        # Read holding registers        response = client.read_holding_registers(start_address, count, slave = unit_id)                if not response.isError():            # Successfully read the registers            return response.registers        else:            print("Error reading Modbus registers")            return None    finally:        # Close the client connection        client.close()# Configuration for the Mitsubishi MELSERVO J4SERIAL_PORT = '/dev/serial0'        # Replace with your actual serial port (e.g., 'COM3' or '/dev/ttyUSB0')BAUDRATE = 115200             # Replace with the baud rate you are usingPARITY = 'N'                # Parity ('N' for None, 'E' for Even, 'O' for Odd)STOPBITS = 2                # Number of stop bits (1 or 2)UNIT_ID = 1                 # The unit ID of your MELSERVO J4START_ADDRESS = 0x6040      # The starting address in hexadecimal (8448 in decimal)REGISTER_COUNT = 1          # We need to read 2 registers to get a 32-bit value# Read registers via serialregisters = read_modbus_registers_via_serial(SERIAL_PORT, BAUDRATE, PARITY, STOPBITS, UNIT_ID, START_ADDRESS, REGISTER_COUNT)if registers:    print("Registers :", registers)else:    print("Failed to read registers")
Writing:

Code:

from pymodbus.client import ModbusSerialClient as ModbusClientfrom pymodbus.payload import BinaryPayloadBuilderfrom pymodbus.constants import Endianimport timedef write_reg(register_address, value, n_byte):    # Create a builder to pack the value into registers    builder = BinaryPayloadBuilder(byteorder=Endian.BIG, wordorder=Endian.BIG)    if(n_byte == 1):        builder.add_8bit_uint(value)        pass    elif(n_byte == 2):        builder.add_16bit_uint(value)        pass    elif(n_byte == 4):        pass        payload = builder.to_registers()    # Writing the registers    try:        response = client.write_registers(register_address, payload, slave = 1)        if not response.isError():            #print(f"Successfully wrote value {value} to register {hex(register_address)}")            print(f"OK")        else:            #print(f"Error writing registers: {response}")            print(f"Error writing registers: {response}")    except Exception as e:        print(f"Exception: {e}")    passif __name__ == "__main__":    # Create Modbus client instance    client = ModbusClient(        method='rtu',        port='/dev/serial0',        baudrate=115200,        parity='N',        stopbits=2,        bytesize=8,        timeout=1    )    connection = client.connect() # Connect to the serial port    if connection:        print("Connected to the Modbus server")    else:        print("Failed to connect to the Modbus server")        print("Enabling Voltage, Quick Stop", end = ": ")    write_reg(0x6040, 6, 2)    time.sleep(0.2)    print("Setting Switch On", end = ": ")    write_reg(0x6040, 7, 2)    time.sleep(0.2)    print("Servo On", end = ": ")    write_reg(0x6040, 15, 2)    time.sleep(0.2)    print("Setting Home Mode", end = ": ")    write_reg(0x6060, 6, 2)    time.sleep(0.2)    print("Setting Actual Position to 0", end = ": ")    write_reg(0x6040, 31, 2)    time.sleep(0.2)    client.close() # Close the client    pass

Statistics: Posted by Tiziano Faver — Tue Jun 18, 2024 11:58 am



Viewing all articles
Browse latest Browse all 1234

Trending Articles