Paolo
Hi !
According to the technical manual for my new sensor, I can configure and read the registers that are important to me :
lecture capteur.png
 
Screenshot 2024-05-21 at 16-28-12 Screenshot.png
 
Screenshot 2024-05-21 at 16-30-32 Screenshot.png
 

But I can't configure the registers that enable the sensor to be set because I get this error message when I add Holding Registers - Write adresses.
 
Modbus Write Holding Registers failed on MB device distance: Illegal function
 
ecriture capteur.png
 
Screenshot 2024-05-21 at 16-36-21 Screenshot.png
 
I'm attaching the sensor manual, thank you
Reply 0 0
thiagoralves
Most likely your sensor does not accept the Modbus Write Multiple Registers function, only the Write Single Register. OpenPLC uses the Write Multiple Registers as that allows many registers to be written once with less overhead. You can either modify OpenPLC Modbus code to match your device (quite complicated), or write a PSM driver that reads the registers for you and make them available in your located variables (%IW, %QW, etc). You can search this forum for more information about PSM, but it is quite simple to use if you know how to write Python. You can enable it on the Hardware tab.
Reply 1 0
Paolo
Crap !
yes this sensor allow only the Write Single Register function 🙁
If I use PSM hardware layer I cannot use Neuron hardware layer ...
😓
Reply 0 0
thiagoralves
Crap !
yes this sensor allow only the Write Single Register function 🙁
If I use PSM hardware layer I cannot use Neuron hardware layer ...
😓
Oh dang! Yeah, I thought you were running this on a Windows PC or something with the blank hardware layer. Your other options is to create a simple python middle layer that acts both as a Modbus Master and Modbus Slave. It can talk to your hardware using the Modbus functions it supports, and also allows OpenPLC to pull in data through Modbus, like a Modbus bridge. I'm pretty sure ChatGPT can write something like that in a snap.
Reply 1 0
Paolo
And there it is, it took me two days with the help of ChatGPT (which makes quite a few mistakes by the way) to come up with a trial version that runs on my Windows PC. Now I just need to adapt it to run on Rpi+Neuron.
 
from pymodbus.client import ModbusSerialClient
from pymodbus.server import StartTcpServer
from pymodbus.device import ModbusDeviceIdentification
from pymodbus.datastore import ModbusSlaveContext, ModbusServerContext, ModbusSequentialDataBlock
from pymodbus.exceptions import ModbusIOException
from threading import Thread, Lock
import time

# Configuration of the PLC IP address and port
PLC_IP = '127.0.0.1'
PLC_PORT = 503

# Configuration of the USB port for the sensor
SENSOR_PORT = 'COM6'  # Port of the sensor, adjusted for COM6
BAUDRATE = 57600

# Addresses of the holding registers that the PLC will read
READ_START_REGISTER = 64
READ_NUM_REGISTERS = 8

# Address of the holding register that the PLC will write to
WRITE_REGISTER = 82

# Reading interval in seconds
INTERVAL = 0.01  # 10 ms

# Slave ID
SLAVE_ID = 1

# Create a Modbus RTU client for the sensor
sensor_client = ModbusSerialClient(
    method='rtu', 
    port=SENSOR_PORT, 
    baudrate=BAUDRATE, 
    timeout=0.1, 
    parity='N', 
    stopbits=1, 
    bytesize=8
)

# Check connection to the sensor
if not sensor_client.connect():
    print("Error connecting to the sensor.")
    exit(1)
else:
    print("Connection to the sensor successful.")

# Create a datastore to store the sensor data
store = ModbusSlaveContext(
    hr=ModbusSequentialDataBlock(0, [0]*100))  # Example with 100 registers
context = ModbusServerContext(slaves=store, single=True)

# Create a lock to synchronize access to shared resources
access_lock = Lock()

# Store the previous value of the register written by the PLC
previous_write_value = None

# Function to read sensor data
def read_sensor_data():
    while True:
        try:
            # Read holding registers from the sensor with the slave ID
            with access_lock:
                response = sensor_client.read_holding_registers(READ_START_REGISTER, READ_NUM_REGISTERS, SLAVE_ID)
            if not response.isError():
                # Update the datastore with the read values from the sensor
                store.setValues(3, READ_START_REGISTER, response.registers)
            else:
                print("Error reading sensor registers:", response)
        except ModbusIOException as e:
            print("Error connecting to the sensor:", e)
        except Exception as e:
            print("Error reading sensor registers:", e)
        
        # Wait before reading again
        time.sleep(INTERVAL)

# Function to write to the sensor
def write_to_sensor(value):
    try:
        # Write the value to the sensor using function code 06 (Write Single Register)
        with access_lock:
            response = sensor_client.write_register(WRITE_REGISTER, value, SLAVE_ID)
        if response.isError():
            print("Error writing to the sensor:", response)
        else:
            print("Write to sensor:", value)
    except ModbusIOException as e:
        print("Error connecting to the sensor:", e)

# Function to check for write requests from the PLC
def check_for_write_request(context):
    global previous_write_value
    while True:
        # Get the value of the register written by the PLC
        write_value = context[SLAVE_ID].getValues(3, WRITE_REGISTER, count=1)[0]
        
        # Check if the value has changed since the last check
        if write_value != previous_write_value:
            # Update the value on the sensor
            write_to_sensor(write_value)
            
            # Update the previous value for the next check
            previous_write_value = write_value
        
        # Wait before checking again
        time.sleep(INTERVAL)

# Modbus server identification
identity = ModbusDeviceIdentification()
identity.VendorName = 'MyCompany'
identity.ProductCode = 'MyProduct'
identity.VendorUrl = 'http://example.com'
identity.ProductName = 'MyModbusDevice'
identity.ModelName = 'MyModel'
identity.MajorMinorRevision = '1.0'

# Function to start the Modbus server
def start_server():
    print("Starting the server...")
    try:
        StartTcpServer(context=context, identity=identity, address=(PLC_IP, PLC_PORT))
    except Exception as e:
        print(f"Error starting the server: {e}")

if __name__ == "__main__":
    # Start a thread to read sensor data
    sensor_thread = Thread(target=read_sensor_data)
    sensor_thread.daemon = True
    sensor_thread.start()

    # Start a thread to check for write requests from the PLC
    write_thread = Thread(target=check_for_write_request, args=(context,))
    write_thread.daemon = True
    write_thread.start()

    # Start the Modbus server
    start_server()
 
Reply 1 0
Reply