The ESP32 Modbus TCP industrial integration is one of the most powerful use cases for this versatile microcontroller. In Indian manufacturing plants, textile units, water treatment facilities, and process industries, Modbus-based PLCs and sensors are ubiquitous. Bridging these legacy systems to modern IoT cloud platforms can dramatically improve visibility, reduce downtime, and enable predictive maintenance — all without replacing expensive existing equipment.
This tutorial walks you through setting up ESP32 as a Modbus TCP master, reading data from industrial PLCs or Modbus-capable sensors, and pushing that data to IoT cloud platforms like AWS IoT, Google Cloud IoT, ThingsBoard, or even a local MQTT broker.
What is Modbus TCP and Why Use It in Industry?
Modbus is one of the oldest and most widely adopted industrial communication protocols, originally developed by Modicon (now Schneider Electric) in 1979. It is simple, robust, and royalty-free, which is why it remains the backbone of countless factories, power plants, and utility systems around the world — including India.
Modbus TCP is the Ethernet-based variant of the Modbus protocol. It wraps traditional Modbus RTU frames inside standard TCP/IP packets, allowing Modbus devices to communicate over Ethernet networks or even the internet. Key characteristics include:
- Master/Slave architecture: One master device polls multiple slave devices for data.
- Function codes: Read Coils (0x01), Read Discrete Inputs (0x02), Read Holding Registers (0x03), Read Input Registers (0x04), Write Single Coil (0x05), Write Single Register (0x06).
- Port 502: Standard TCP port for Modbus communication.
- 16-bit registers: Data is stored in 16-bit holding registers, readable by the master.
In Indian industry, you’ll find Modbus TCP or Modbus RTU (RS-485) on energy meters (Secure, L&T), VFDs (ABB, Siemens), PLCs (Delta, Mitsubishi, Siemens S7), and water quality sensors. Converting this data to cloud-readable MQTT or HTTP opens up dashboards, alerts, and analytics without touching the control system.
ESP32 as a Modbus TCP Master
The ESP32 is an excellent choice as a Modbus TCP master (also called a Modbus TCP client) for IIoT gateway applications. Here’s why:
- Built-in Wi-Fi and Ethernet support: Connect to your plant LAN via Wi-Fi or, with an Ethernet module (W5500, ENC28J60), via wired Ethernet for higher reliability.
- Dual-core processor: Dedicate one core to Modbus polling and another to cloud communication.
- FreeRTOS: Task scheduling for deterministic polling intervals.
- TLS/SSL support: Secure MQTT over TLS for cloud connectivity.
- Price: An ESP32 module costs ₹200-₹400 in India — far cheaper than any industrial IoT gateway.
The ESP32 can simultaneously act as a Modbus TCP master (reading PLC data), an MQTT client (publishing to cloud), and a local web server (showing a real-time dashboard on your phone). This multi-role capability is what makes it ideal for retrofitting existing industrial equipment.
Ai Thinker NodeMCU-32S ESP32 Development Board – IPEX Version
A reliable 38-pin ESP32 development board with IPEX antenna connector for use in metal enclosures or areas requiring extended range — perfect for industrial deployments.
Hardware Setup and Wiring
For a typical ESP32 Modbus TCP industrial gateway, you’ll need:
- ESP32 development board
- Plant LAN access (Ethernet switch connected to PLC and ESP32 via Wi-Fi AP, or direct Ethernet via W5500 module)
- Power supply — 5V DC or 3.3V; consider a 18650 battery shield for UPS capability
- Optional: RS-485 to TTL converter if bridging Modbus RTU devices
Most Modbus TCP devices (PLCs, energy meters) connect directly over Ethernet. The ESP32 joins the same subnet and polls the PLC’s IP address on port 502. No additional wiring is needed beyond standard LAN infrastructure.
If your industrial device only has RS-485 (Modbus RTU), you’ll need a MAX485 or RS-485 module. The ESP32 communicates with the RS-485 transceiver via UART, and you’ll use a Modbus RTU library instead. However, in this tutorial we focus on Modbus TCP.
Network topology:
PLC (Modbus TCP Slave, IP: 192.168.1.100)
|
[Ethernet Switch]
|
[Wi-Fi Access Point]
|
ESP32 (Modbus TCP Master, MQTT Client)
|
[Internet]
|
MQTT Broker (ThingsBoard / AWS IoT)
2 x 18650 Lithium Battery Shield for ESP32/ESP8266
Provides UPS capability for your ESP32 IIoT gateway — keeps it running during brief power outages common in Indian industrial environments.
Firmware, Libraries, and Code
The easiest way to implement Modbus TCP on ESP32 is using the Arduino IDE or PlatformIO with the ArduinoModbus library (by Arduino) or the ModbusMaster library. For TCP specifically, use the ArduinoModbus library which wraps ArduinoRS485 and supports Modbus TCP over standard WiFiClient.
Step 1: Install Required Libraries
In Arduino IDE, install:
ArduinoModbusby ArduinoArduinoRS485by ArduinoPubSubClientby Nick O’Leary (for MQTT)ArduinoJsonby Benoit Blanchon
Step 2: Basic Modbus TCP Read Code
#include <WiFi.h>
#include <ArduinoModbus.h>
#include <PubSubClient.h>
#include <ArduinoJson.h>
const char* ssid = "YourPlantWiFi";
const char* password = "YourPassword";
const char* mqttServer = "your-broker.com";
const int mqttPort = 1883;
const char* plcIP = "192.168.1.100";
ModbusTCPClient modbusTCPClient(WiFiClient());
WiFiClient wifiClient;
PubSubClient mqttClient(wifiClient);
void setup() {
Serial.begin(115200);
WiFi.begin(ssid, password);
while (WiFi.status() != WL_CONNECTED) delay(500);
mqttClient.setServer(mqttServer, mqttPort);
mqttClient.connect("ESP32-IIoT-Gateway");
}
void loop() {
if (!modbusTCPClient.connected()) {
modbusTCPClient.begin(plcIP, 502);
}
// Read Holding Registers: start=0, count=5
if (modbusTCPClient.requestFrom(INPUT_REGISTERS, 0, 5)) {
StaticJsonDocument<256> doc;
doc["temperature"] = modbusTCPClient.read() / 10.0;
doc["pressure"] = modbusTCPClient.read();
doc["flow_rate"] = modbusTCPClient.read();
doc["status"] = modbusTCPClient.read();
doc["alarm"] = modbusTCPClient.read();
char payload[256];
serializeJson(doc, payload);
mqttClient.publish("plant/machine1/telemetry", payload);
}
delay(5000); // Poll every 5 seconds
}
Step 3: FreeRTOS Dual-Task Architecture
For production deployments, separate Modbus polling and MQTT publishing into two FreeRTOS tasks. This prevents a slow Modbus poll from blocking cloud publishing and vice versa. Use a QueueHandle_t to pass data between tasks safely.
QueueHandle_t dataQueue;
// Task 1: Modbus polling (Core 1)
void modbusTask(void* parameter) {
for(;;) {
// Read registers, push to queue
SensorData data;
// ... modbus reads ...
xQueueSend(dataQueue, &data, portMAX_DELAY);
vTaskDelay(5000 / portTICK_PERIOD_MS);
}
}
// Task 2: MQTT publishing (Core 0)
void mqttTask(void* parameter) {
for(;;) {
SensorData data;
if (xQueueReceive(dataQueue, &data, portMAX_DELAY)) {
// Serialize and publish
}
}
}
void setup() {
dataQueue = xQueueCreate(10, sizeof(SensorData));
xTaskCreatePinnedToCore(modbusTask, "Modbus", 4096, NULL, 1, NULL, 1);
xTaskCreatePinnedToCore(mqttTask, "MQTT", 4096, NULL, 1, NULL, 0);
}
IoT Cloud Integration via MQTT
Once data is on MQTT, you can route it to virtually any IoT cloud platform:
ThingsBoard (Self-hosted or Cloud)
ThingsBoard is popular in Indian IIoT deployments because you can self-host it on a ₹500/month VPS. Connect ESP32 using the ThingsBoard MQTT API, and your PLC data auto-populates in dashboards with gauges, charts, and alarm rules.
AWS IoT Core
For enterprise-grade deployments, AWS IoT Core with TLS certificates offers device authentication, rule-based routing to DynamoDB or S3, and integration with AWS QuickSight for analytics.
Node-RED + InfluxDB + Grafana
This open-source stack is extremely popular with Indian engineers. Node-RED subscribes to your ESP32’s MQTT topics, flows data into InfluxDB (time-series DB), and Grafana visualizes it. You can run this entire stack on a Raspberry Pi on-premise.
30Pin ESP32 Expansion Board with Type-C USB and Micro USB Interface
Makes prototyping your Modbus TCP gateway faster with convenient breakout pins and dual USB interface for easy programming and power.
Real-World IIoT Use Cases in India
Indian industries are rapidly adopting IIoT to comply with BEE (Bureau of Energy Efficiency) energy audit requirements and to improve OEE (Overall Equipment Effectiveness). Here are proven use cases where ESP32 + Modbus TCP delivers real value:
1. Energy Monitoring in Textile Mills
Gujarat and Maharashtra textile mills use Secure or L&T energy meters with Modbus RTU/TCP. An ESP32 gateway reads kWh, kVAh, power factor, and voltage from all feeders every 15 seconds, publishing to a ThingsBoard dashboard. Energy managers spot load imbalances and motor inefficiencies in real time.
2. Water Treatment SCADA Replacement
Municipal water treatment plants in Tier-2 Indian cities run aging SCADA systems. ESP32 gateways can read flow meters, pH sensors, and chlorination dosing pumps via Modbus TCP and push data to a cloud dashboard — at a fraction of the cost of a full SCADA upgrade.
3. Injection Moulding Machine Monitoring
Delta PLCs in injection moulding machines expose process data (cycle time, melt temperature, injection pressure) via Modbus TCP. ESP32 reads this and calculates OEE, posting shift reports to WhatsApp via Twilio API — a feature Indian factory managers love.
4. Compressor Room Monitoring
Industrial compressors fitted with ABB or Danfoss VFDs expose speed, current, and fault codes via Modbus TCP. ESP32 monitors these and triggers alerts when a compressor approaches its fault threshold, enabling preventive maintenance before a costly breakdown.
5. Solar Inverter Monitoring
Many Indian rooftop solar installations use Solis, Growatt, or Fronius inverters with Modbus TCP/RS-485 ports. ESP32 reads inverter data and posts to a custom dashboard, giving site managers real-time yield monitoring without paying for inverter manufacturer cloud subscriptions.
BMP280 Barometric Pressure and Altitude Sensor I2C/SPI Module
Complement your Modbus TCP data with local ambient pressure and temperature readings from this accurate BMP280 module alongside industrial PLC data.
Frequently Asked Questions
Can ESP32 handle multiple Modbus TCP slave connections simultaneously?
Yes. ESP32 can maintain multiple TCP connections in a round-robin polling loop. However, each connection consumes RAM and socket resources. Practically, polling 5-10 Modbus TCP slaves at 5-10 second intervals is well within ESP32’s capability. For more slaves, increase the polling interval or use ESP32’s dual-core architecture with dedicated tasks per slave group.
What is the maximum Modbus TCP polling rate achievable with ESP32?
On a local LAN with low latency, ESP32 can poll a Modbus TCP device at approximately 10-20 requests per second per slave. A typical request-response cycle including TCP overhead takes 20-50ms. Network congestion and PLC response times are usually the bottleneck, not the ESP32.
Is it safe to connect ESP32 directly to an industrial PLC network?
With proper network segmentation, yes. Use a separate VLAN for the Modbus TCP polling network and the ESP32’s internet-facing interface. Never bridge plant-level OT (Operational Technology) networks directly to the internet. Always use a firewall or VPN for cloud connectivity.
What happens if the Wi-Fi connection drops during Modbus polling?
Implement local data buffering on ESP32 using SPIFFS or LittleFS. Store polled data in JSON files when MQTT is unavailable, and flush the buffer once the connection is restored. This prevents data loss during brief connectivity interruptions common in Indian industrial environments with 4G/Wi-Fi backhaul.
Can I use ESP32 with Modbus RTU (RS-485) instead of Modbus TCP?
Absolutely. Use a MAX485 module with ESP32’s UART, and use the ModbusMaster library instead of ArduinoModbus. Many Indian energy meters and older PLCs use RS-485. You can even build a Modbus RTU-to-TCP gateway where ESP32 reads RS-485 devices and presents their data as Modbus TCP registers to a SCADA system.
Build Your IIoT Gateway with ESP32 from Zbotic
Zbotic.in stocks a wide range of ESP32 development boards, sensors, power modules, and accessories suitable for industrial IoT applications. From basic NodeMCU boards to advanced S3-based modules with displays, find everything you need to build a robust Modbus TCP gateway for your plant.
Add comment