Maverick1603
Hello everyone,
I have an ESP32 running as a Modbus TCP slave that sends distance data from an ultrasonic sensor to a Raspberry Pi running OpenPLC. The Raspberry Pi acts as both a Modbus client (reading data from the ESP32) and a Modbus server (sending that data to OpenPLC).
Everything works, but I noticed in the OpenPLC runtime logs that the ESP32 disconnects every time it gets polled by the Raspberry Pi.

Current Setup

  1. ESP32 – Runs a Modbus TCP slave and serves the ultrasonic sensor data.
  2. Raspberry Pi
    • Reads distance data from ESP32 (Modbus client).
    • Sends that data to OpenPLC (Modbus server).
    • Reads a coil from OpenPLC to turn an LED on/off.

Issue

In the OpenPLC runtime logs, I see that the ESP32 disconnects after each polling request from the Raspberry Pi. However, everything still works fine.

OpenPLC Setup

[203128%2F9261016%2Fmceclip0]

Raspberry Pi code:

from pymodbus.client import ModbusTcpClient
import RPi.GPIO as GPIO
import time

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

# Modbus configuration (Pi as Modbus client to read from ESP32)
ESP32_IP = "172.x.x.10"  # IP of ESP32 running Modbus TCP slave
MODBUS_PORT = 502
client = ModbusTcpClient(ESP32_IP, port=MODBUS_PORT, timeout=5)

# Modbus configuration (Pi as Modbus server to update OpenPLC)
OPENPLC_IP = "172.x.x.9"  # IP of Modbus server (OpenPLC) on Pi
client_openplc = ModbusTcpClient(OPENPLC_IP, port=502)

# Connect to Modbus server (ESP32) and OpenPLC (Pi)
client.connect()
client_openplc.connect()

while True:
    try:
        # Check if the clients are connected
        if not client.is_socket_open():
            client.connect()
        if not client_openplc.is_socket_open():
            client_openplc.connect()

        # Read the distance value from ESP32 (Modbus register 0)
        response = client.read_holding_registers(address=0, count=1)
        if not response.isError():
            distance = response.registers[0]
            client_openplc.write_register(1024, distance)  # Send to OpenPLC

        # Read the output coil from OpenPLC (%QX0.0)
        response_led = client_openplc.read_coils(address=0, count=1)
        if not response_led.isError():
            GPIO.output(LED_PIN, GPIO.HIGH if response_led.bits[0] else GPIO.LOW)

        time.sleep(0.5)

    except Exception:
        client.close()
        client_openplc.close()
        time.sleep(2)  # Wait before reconnecting
        client.connect()
        client_openplc.connect()

# Close Modbus clients when done
client.close()
client_openplc.close()

ESP32 code:

#include <WiFi.h>
#include <ModbusTCPSlave.h>
#include "Ultrasonic.h"

// Wi-Fi credentials
const char *ssid = "SSID";
const char *password = "mypasswrd";

// Define the ultrasonic sensor
Ultrasonic ultrasonic(4);  // GPIO 4 for Trigger and Echo

// ModbusTCP Setup
WiFiServer server(MODBUS_TCP_SLAVE_DEFAULT_PORT);
ModbusTCPSlave modbus;

const uint8_t numHoldingRegisters = 1;
uint16_t holdingRegisters[numHoldingRegisters];

WiFiClient client;  // Persistent client connection

void setup() {
    Serial.begin(115200);
    WiFi.begin(ssid, password);

    while (WiFi.status() != WL_CONNECTED) {
        delay(1000);
    }

    server.begin();
    modbus.configureHoldingRegisters(holdingRegisters, numHoldingRegisters);
}

void ensureWiFiConnected() {
    if (WiFi.status() != WL_CONNECTED) {
        WiFi.begin(ssid, password);
        while (WiFi.status() != WL_CONNECTED) {
            delay(1000);
        }
    }
}

void loop() {
    ensureWiFiConnected();

    // Check for a new client connection if no client is currently connected
    if (!client || !client.connected()) {
        client = server.available();
    }

    // Process Modbus requests if a client is connected
    if (client) {
        long distance = ultrasonic.MeasureInCentimeters();
        holdingRegisters[0] = distance; // Update Modbus register with distance

        modbus.poll(client); // Process Modbus requests
    }

}

Questions:

Is it normal for a Modbus TCP connection to disconnect after each polling request? Should I be concerned about these disconnections, or is this just how OpenPLC handles polling?
Any advice would be greatly appreciated! Thanks in advance
 
 
Reply 0 0
thiagoralves
Why haven’t you configured the ESP32 as an OpenPLC slave device directly? I don’t understand why you need to create an intermediate Python program and also code a custom Modbus Arduino implementation. Just use OpenPLC for everything and you’ll be good. See https://autonomylogic.com/docs/2-6-slave-devices/
Reply 0 0
Maverick1603
Why haven’t you configured the ESP32 as an OpenPLC slave device directly? I don’t understand why you need to create an intermediate Python program and also code a custom Modbus Arduino implementation. Just use OpenPLC for everything and you’ll be good. See https://autonomylogic.com/docs/2-6-slave-devices/
I’ve tried for a week straight to get this working, but for some reason, it just doesn’t work. I’ve tried with two different ESP32 models: the XIAO ESP32 C6 and the ESP32-D0WD-V3, but I’m running into the same issues.
I understand your suggestion about configuring the ESP32 as an OpenPLC slave device directly, and I agree that using OpenPLC for everything would be the best approach. However, when I try to upload the OpenPLC project to the ESP32, I get the following errors:
In file included from C:\Users\mzero\OpenPLC_Editor\editor\arduino\src\POUS.h:4,
                 from C:\Users\mzero\OpenPLC_Editor\editor\arduino\src\POUS.c:1:
C:\Users\mzero\OpenPLC_Editor\editor\arduino\src\POUS.c: In function 'PROGRAM0_init__':
editor\arduino\src\lib/accessor.h:71:30: error: implicit declaration of function '__GET_GLOBAL_DISTANCE' [-Wimplicit-function-declaration]
   71 |                 name.value = __GET_GLOBAL_##global();\
      |                              ^~~~~~~~~~~~~
C:\Users\mzero\OpenPLC_Editor\editor\arduino\src\POUS.c:4:3: note: in expansion of macro '__INIT_EXTERNAL'
    4 |   __INIT_EXTERNAL(INT,DISTANCE,data__->DISTANCE,retain)
      |   ^~~~~~~~~~~~~~~
editor\arduino\src\lib/accessor.h:71:28: error: assignment to 'IEC_INT *' {aka 'short int *'} from 'int' makes pointer from integer without a cast [-Wint-conversion]
   71 |                 name.value = __GET_GLOBAL_##global();\
      |                            ^
C:\Users\mzero\OpenPLC_Editor\editor\arduino\src\POUS.c:4:3: note: in expansion of macro '__INIT_EXTERNAL'
    4 |   __INIT_EXTERNAL(INT,DISTANCE,data__->DISTANCE,retain)
 

What I've Tried:

  • I’ve tried the setup with two different ESP32 models: XIAO ESP32 C6 and ESP32-D0WD-V3, but I get the same errors.
  • I’ve followed the instructions for setting up OpenPLC with Modbus and using ESP32 as a slave device.

Additional Details:

  • The project compiles and uploads fine to an Arduino, but not the ESP32.
  • I’ve checked the necessary libraries and dependencies for ESP32, but I’m still getting these errors.
I will also attach the project in a zip file, in case it helps. Any suggestions or insights would be greatly appreciated!
Reply 0 0
thiagoralves
From the error you’ve sent I can tell you’re not following the instructions to upload the blank program to make the ESP32 a slave. The blank program is blank, and shouldn’t contain any variables. It seems that you’re trying to upload your main program to the ESP32. This should be fine as well. The issue you’re having seems to be related to global variables. See this post to fix it: https://openplc.discussion.community/post/compilation-suddenly-failing-13591556
Reply 0 0
Maverick1603
From the error you’ve sent I can tell you’re not following the instructions to upload the blank program to make the ESP32 a slave. The blank program is blank, and shouldn’t contain any variables. It seems that you’re trying to upload your main program to the ESP32. This should be fine as well. The issue you’re having seems to be related to global variables. See this post to fix it: https://openplc.discussion.community/post/compilation-suddenly-failing-13591556
I’ve uploaded the blank program to my ESP32 (XIAO ESP32C6) as a Modbus TCP slave using the latest version of OpenPLC. After modifying the hals.json file appropriately, uploading works fine now.
However, I noticed that when I upload the blank project, the %IW100 variable in the OpenPLC Runtime shows unexpected or seemingly random values. I suspect these are raw sensor readings coming from the ESP32.

Is it possible to decode or use these values directly in the Ladder Logic program within OpenPLC Runtime, or do I need to implement additional code on the ESP32 side to interpret and format the sensor data correctly before sending it? I've tried to but don't really know where to start.
Reply 0 0
thiagoralves
IW100 on the master is mapped to IW0 on the slave, which contains the pure analog reading of the analog pin. This reading is from the 0-65535 range and is linearly equivalent to the voltage reading in your analog input pin
Reply 0 0
Maverick1603
IW100 on the master is mapped to IW0 on the slave, which contains the pure analog reading of the analog pin. This reading is from the 0-65535 range and is linearly equivalent to the voltage reading in your analog input pin
Thank you again for the quick reply.

So basically, to get actual sensor values into %IW or %MW registers on the Raspberry Pi (running OpenPLC Runtime), I would need to use a custom Modbus TCP library on the ESP32 to read the sensors and manually push their data into the Modbus registers — is that the correct approach?
Reply 0 0
thiagoralves
It depends on which type of sensors you have. If you have pure analog sensors (i.e. those that use voltage or current to measure things) then you can have the ESP32 be like a dumb slave and just send over raw values, and then treat the values on the master side with some math to convert the raw analog values into voltage / current, and then finally to the measurement unit.
 
If you have a smart sensor that communicates digitally, then you will have to treat the value locally on the ESP32. I don’t know what type of project you’re trying to work on and what is the project’s topology. But in case of sensors like that you could move some of the logic (if not most of the logic) to the ESP32 itself using OpenPLC + Arduino Extension and then have the master supervise just the “big picture”. Depending on the complexity of the project you might not even need the master at all, and have the ESP32 hooked up directly to an HMI
Reply 1 0
Reply