Maverick1603
Hi everyone,
I'm working on a small test where I’m using a Raspberry Pi with an ultrasonic sensor (Grove Ultrasonic Ranger) and a LED controlled via Modbus communication with OpenPLC.
I’ve written some Python code to read the distance from the sensor and send it via Modbus to OpenPLC. If the distance is less than 50 cm, I want the LED to turn on. Here’s the code I’ve written so far:

from pymodbus.client import ModbusTcpClient
import RPi.GPIO as GPIO
import time
from grove.grove_ultrasonic_ranger import GroveUltrasonicRanger

# Define GPIO for LED
LED_PIN = 16
GPIO.setmode(GPIO.BCM)
GPIO.setup(LED_PIN, GPIO.OUT)

# Modbus configuration
MODBUS_SERVER = "127.0.0.1"
MODBUS_PORT = 502
client = ModbusTcpClient(MODBUS_SERVER, port=MODBUS_PORT)

# Ultrasonic sensor on D5
sensor = GroveUltrasonicRanger(5)

# Connect to Modbus server
client.connect()

while True:
    try:
        # Read distance
        distance = int(sensor.get_distance())
        print(f"Distance: {distance} cm")

        # Ensure distance is an integer
        distance = int(distance)

        # Send value to OpenPLC (write to %MW0)
        client.write_register(0, distance)  # %MW0 in OpenPLC
        time.sleep(0.1)  # Small delay to ensure the value is processed

        # Read the output coil from OpenPLC (e.g., %QX0.0)
        response = client.read_coils(address=0, count=1)

        if response.isError():
            print(f"Error reading coils: {response}")
        else:
            if response.bits[0]:  # If OpenPLC activates the coil
                GPIO.output(LED_PIN, GPIO.HIGH)
            else:
                GPIO.output(LED_PIN, GPIO.LOW)

        time.sleep(1)

    except Exception as e:
        print(f"Error: {e}")

# Close the Modbus client after the loop ends
client.close()
This code works, but I’m facing an issue where the values in OpenPLC don't update. The distance value remains at 0, and the output remains TRUE in the monitoring window of the OpenPLC browser even when the sensor is reading values above 50.
Here’s what my OpenPLC editor setup looks like:

[203128%2F9252507%2Fmceclip0]
 
I’m not sure if the distance value is being sent correctly to the register. Any help or insights would be greatly appreciated.
Thanks in advance!
Reply 0 0
thiagoralves
%MW0 is at address 1024, not 0. See https://autonomylogic.com/docs/2-5-modbus-addressing/
 
Also, make sure you’re in the latest release of the OpenPLC runtime on your Pi. There has been a recent fix specifically on MW0
Reply 1 0
Maverick1603
%MW0 is at address 1024, not 0. See https://autonomylogic.com/docs/2-5-modbus-addressing/
 
Also, make sure you’re in the latest release of the OpenPLC runtime on your Pi. There has been a recent fix specifically on MW0
I feel so stupid for missing that. It works now, thanks a lot for the quick response and the help, really appreciate it!
Reply 1 0
Reply