perkun.eu Services Portfolio Blog About Contact PL
← Blog

4/28/2022

ESP32 and Modbus RTU — reading data from industrial sensors

TL;DR: ESP32 + RS485 converter + ModbusMaster library = a gateway to the world of industrial sensors. Costs < 30 PLN and works with any Modbus RTU device.

Modbus RTU is a protocol from 1979 that is today the standard in industrial automation. Energy meters, temperature and humidity sensors, PLC controllers — if they have an RS485 interface and Modbus RTU, you can talk to them through an ESP32.

Hardware (< 30 PLN total)

  • ESP32 (e.g. DevKitC) — ~15 PLN
  • TTL-RS485 converter (MAX485 or SP3485) — ~3 PLN
  • Cable to the sensor

Wiring: ESP32 TX → converter DI, RX → RO, GPIO to control DE/RE (RS485 transmission direction is half-duplex).

#define RXD2 16
#define TXD2 17
#define DE_RE 4  // pin controlling RS485 direction

void setup() {
  Serial2.begin(9600, SERIAL_8N1, RXD2, TXD2);
  pinMode(DE_RE, OUTPUT);
  digitalWrite(DE_RE, LOW);  // receive mode
}

ModbusMaster library

#include <ModbusMaster.h>

ModbusMaster node;

void preTransmission() { digitalWrite(DE_RE, HIGH); }
void postTransmission() { digitalWrite(DE_RE, LOW); }

void setup() {
  node.begin(1, Serial2);  // slave address = 1
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);
}

void loop() {
  uint8_t result = node.readHoldingRegisters(0x0000, 2);
  if (result == node.ku8MBSuccess) {
    float temperatura = node.getResponseBuffer(0) / 10.0;
    Serial.printf("Temperatura: %.1f°C\n", temperatura);
  }
  delay(5000);
}

Common pitfalls

Slave address: every Modbus device has an address (1–247). Check the documentation — the factory default is often 1, but it may differ.

Baud rate: the standard is 9600, but many devices use 4800 or 19200. Check the documentation or the physical switch on the device.

Holding vs Input registers: read-only data is often in Input Registers (function 04), configuration parameters in Holding Registers (function 03). Wrong function = timeout or error.

DE/RE timing: switching the DE/RE pin too quickly causes transmission errors. Add delayMicroseconds(100) after changing direction if you see random errors.

Next steps

Got data from the sensor? Now: MQTT publish every 60s → Mosquitto broker → InfluxDB → Grafana. That’s the standard IoT stack we cover in a separate article.