Skip to Content

Modbus RTU master and slave with two ESP32 PLC, step by step

Short answer: connect the RS-485 ports of two ESP32 PLC A+ to A+ and B- to B-, with a 120 Ω resistor at each end of the bus, open both ports with RS485.begin(19200, HALFDUPLEX, SERIAL_8E1) and use the Industrial Shields Modbus library: ModbusRTUSlave answers from four arrays when you call update(), and ModbusRTUMaster sends one request at a time and reads the answer with available().

This tutorial builds a Modbus RTU link between two ESP32 PLC: one is the master and the other is the slave with ID 1. It covers the wiring, the Modbus map, the board and the library in the Arduino IDE, the full code of both PLCs and the serial output to expect. The same library also runs on Arduino PLC with hardware RS-485; the pin names and the RS-485 switches change with the model.

What you build

Only the master starts a conversation, one request at a time, and the slave answers. Every second the master sends the next request of this cycle:

  • Write coil 0: the slave switches its digital output Q0_0 on or off.
  • Write holding register 0: a setpoint from 0 to 4095, which the slave copies to its analog output A0_5.
  • Read input registers 0 and 1: the raw value of the analog input I0_7 and the seconds since the slave started.

Wiring

Half duplex RS-485 on one twisted pair. Power both PLCs with 12 to 24 Vdc.

Modbus RTU over RS-485: two ESP32 PLC ESP32 PLC 21+ MASTER ESP32 PLC 21+ SLAVE ID 1 A+B-GND A+B-GND A+ to A+ B- to B- (twisted pair) signal GND (if no common reference) 120 Ω at this end 120 Ω at this end Both ends: 19200 baud, 8E1, half duplex. ESP32 PLC: check the RS-485 switch (Switch 3 OFF per Industrial Shields guide). Termination only at the two physical ends of the bus. Polarity names (A/B) can be swapped between brands: if nothing answers, try swapping.

Diagram: master on the left, slave with ID 1 on the right, a 120 Ω termination resistor at each end of the bus and the signal ground as an option.

  • A+ to A+, B- to B-: on a twisted pair. Some devices from other brands label A and B the other way round.
  • Termination: a 120 Ω resistor at each physical end of the bus, and only there.
  • Signal ground: connect GND too when the devices have no common reference.
  • ESP32 PLC: check the RS-485 switch in the Industrial Shields guide for your model. The Modbus RTU guide gives Switch 3 OFF for the ESP32 PLC family.
  • Port settings: 19200 baud, 8 data bits, even parity and 1 stop bit (8E1) on both PLCs.

Modbus map (slave ID 1)

Addresses are protocol addresses, from 0: index 0 of each array in the slave is address 0. If a manual numbers registers from 1 (40001 and so on), see the lesson on register 40001.

TableAddressWhat it is
Coil0Digital output Q0_0 of the slave
Discrete input0Digital input I0_0
Holding register0Setpoint from 0 to 4095, copied to the analog output A0_5
Input register0Raw value of the analog input I0_7
Input register1Seconds since the slave started (low 16 bits)

Board and library

  1. In the Arduino IDE, open File > Preferences and add https://apps.industrialshields.com/main/arduino/boards/package_industrialshields_index.json to "Additional boards manager URLs".
  2. Open the Boards Manager (Tools > Board > Boards Manager), search for "industrialshields" and install "industrialshields-esp32". This tutorial uses version 2.7.1.
  3. Select Tools > Board > Industrial Shields ESP32 Boards > ESP32 PLC Family, then your PLC in Tools > Model (for example ESP32 PLC 21 IO+).
  4. Add the Industrial Shields Modbus library: download it from GitHub (Industrial-Shields/arduino-Modbus) and install it with Sketch > Include Library > Add .ZIP Library. This tutorial uses version 1.1.0, and its examples appear in File > Examples > Modbus.
  5. Upload the slave code to one PLC and the master code to the other, then open the Serial Monitor of each one at 115200 baud.

Slave code

The slave opens RS-485 with 8E1 and gives the library four arrays: coils, discrete inputs, holding registers and input registers. In the loop it refreshes the inputs, calls update() so that the library answers any request, and copies what the master wrote to the outputs.

// ESP32 PLC as Modbus RTU slave (address 1) over RS-485
// Library: Modbus 1.1.0 by Industrial Shields (github.com/Industrial-Shields/arduino-Modbus). Board: industrialshields:esp32:esp32plc
// Map:
//   Coil 0            -> digital output Q0_0
//   Discrete input 0  <- digital input I0_0
//   Holding reg 0     -> setpoint written by the master (0..4095), copied to analog output A0_5
//   Input reg 0       <- analog input I0_7 (raw ADC value)
//   Input reg 1       <- seconds since boot (low 16 bits)

#include <RS485.h>
#include <ModbusRTUSlave.h>

const uint8_t  SLAVE_ID = 1;
const uint32_t BAUD     = 19200UL;    // must match the master
ModbusRTUSlave slave(RS485, SLAVE_ID);

bool     coils[1];
bool     discreteInputs[1];
uint16_t holdingRegisters[1];
uint16_t inputRegisters[2];

void setup() {
  Serial.begin(115200UL);
  pinMode(Q0_0, OUTPUT);
  pinMode(I0_0, INPUT);

  RS485.begin(BAUD, HALFDUPLEX, SERIAL_8E1);   // 8 data bits, even parity, 1 stop bit
  slave.begin(BAUD);

  slave.setCoils(coils, 1);
  slave.setDiscreteInputs(discreteInputs, 1);
  slave.setHoldingRegisters(holdingRegisters, 1);
  slave.setInputRegisters(inputRegisters, 2);
  Serial.println("Modbus RTU slave ready, ID 1");
}

void loop() {
  // 1. Refresh what the master can read
  discreteInputs[0] = digitalRead(I0_0);
  inputRegisters[0] = analogRead(I0_7);
  inputRegisters[1] = (uint16_t)(millis() / 1000UL);

  // 2. Answer any pending request (call it often, never block the loop)
  slave.update();

  // 3. Apply what the master wrote
  digitalWrite(Q0_0, coils[0]);
  analogWrite(A0_5, holdingRegisters[0]);
}

update() answers a request when it arrives and does not block. It has to run often: long delays in the loop can make the master time out.

Master code

The master uses the same port settings and sends one request per second, and only when it is not waiting for an answer. The functions do not block, so the loop checks available() for the response.

// ESP32 PLC as Modbus RTU master over RS-485
// Library: Modbus 1.1.0 by Industrial Shields (github.com/Industrial-Shields/arduino-Modbus). Board: industrialshields:esp32:esp32plc
// Every second, one request at a time:
//   step 0: write coil 0 of slave 1 (toggles Q0_0 on the slave)
//   step 1: write holding register 0 (setpoint)
//   step 2: read input registers 0..1 (analog value and uptime)

#include <RS485.h>
#include <ModbusRTUMaster.h>

const uint8_t  SLAVE_ID = 1;
const uint32_t BAUD     = 19200UL;    // must match the slave
ModbusRTUMaster master(RS485);

uint8_t  step = 0;
bool     coilState = false;
uint16_t setpoint = 0;
uint32_t lastRequest = 0;
bool     pending = false;      // a request is on the bus

void setup() {
  Serial.begin(115200UL);
  RS485.begin(BAUD, HALFDUPLEX, SERIAL_8E1);
  master.begin(BAUD);
  Serial.println("Modbus RTU master ready");
}

void sendNext() {
  bool sent = false;
  switch (step) {
    case 0: sent = master.writeSingleCoil(SLAVE_ID, 0, coilState); break;
    case 1: sent = master.writeSingleRegister(SLAVE_ID, 0, setpoint); break;
    case 2: sent = master.readInputRegisters(SLAVE_ID, 0, 2); break;
  }
  if (sent) pending = true;
  else Serial.println("Request not sent (bus busy)");
}

void loop() {
  // The library drops the request silently after its timeout (1 s by default): report it
  if (pending && !master.isWaitingResponse()) {
    Serial.println("No answer from slave: check wiring A/B, termination, ID, baud and parity");
    pending = false;
  }

  // One request per second, and never while waiting for an answer
  if (!master.isWaitingResponse() && millis() - lastRequest >= 1000UL) {
    sendNext();
    lastRequest = millis();
  }

  if (master.isWaitingResponse()) {
    ModbusResponse response = master.available();
    if (response) {
      pending = false;
      if (response.hasError()) {
        Serial.print("Modbus exception ");
        Serial.println(response.getErrorCode());
      } else if (step == 2) {
        Serial.print("I0_7 raw: ");
        Serial.print(response.getRegister(0));
        Serial.print("  slave uptime s: ");
        Serial.println(response.getRegister(1));
      }
      if (step == 0) coilState = !coilState;
      if (step == 1) setpoint = (setpoint + 512) % 4096;
      step = (step + 1) % 3;
    }
  }
}

If the slave does not answer, the library drops the request after its timeout (1000 ms by default) and prints nothing, so this sketch prints its own message when isWaitingResponse() turns false and no answer has arrived. The library also records the timeout as an exception, which you can read with hasException() and getExceptionMessage(), as the Industrial Shields guide does. A false from writeSingleCoil(), writeSingleRegister() or readInputRegisters() means that the request was not sent, not that the slave failed.

Expected serial output

Output of master and slave together, from the test described below:

Modbus RTU slave ready, ID 1
Modbus RTU master ready
[ 0.000 s] SLAVE Q0_0 -> 0
[ 0.000 s] SLAVE A0_5 -> 0
I0_7 raw: 2345  slave uptime s: 3
[ 4.003 s] SLAVE Q0_0 -> 1
[ 5.003 s] SLAVE A0_5 -> 512
I0_7 raw: 2345  slave uptime s: 6

This output is not from hardware. Both sketches were compiled with the Industrial Shields ESP32 boards 2.7.1 and the Modbus library 1.1.0, without errors or warnings in the sketch code, and then run against the library with a simulated RS-485 bus. The lines in square brackets are the log of the simulation, which shows the outputs of the slave; the sketches do not print them. The cycle has three requests, one per second, so each value changes every three seconds: Q0_0 toggles, the setpoint goes up in steps of 512 and the master prints the analog value and the uptime of the slave. The raw value of I0_7 (2345) comes from the simulation; on a PLC it depends on the signal and on the input range of your model.

If nothing answers

  • A and B: some devices label them the other way round. If nothing answers, swap them.
  • Termination: one 120 Ω resistor at each of the two physical ends of the bus, none in the middle.
  • RS-485 switch: on ESP32 PLC, as the Industrial Shields guide says for your model.
  • Slave ID: SLAVE_ID is 1 in both sketches.
  • Baud rate, parity and stop bits: the same on both PLCs, in RS485.begin() and in begin() of the master and the slave.
  • "Request not sent (bus busy)": the master was still waiting for an answer, or the slave address is 0 or above 247.
  • "Modbus exception" followed by a code: the slave answered, and the request is the problem. Code 2, Illegal Data Address, points to an address or a quantity outside the arrays of the slave.
  • A slave that answers late or not at all: look for delays or blocking code in its loop.

Next steps

Sources

Industrial Shields: Modbus RTU with Arduino and ESP32 based PLCs (wiring, 8E1, RS-485 switch of the ESP32 PLC, default timeout), the Modbus library 1.1.0 on GitHub (Industrial-Shields/arduino-Modbus) and the Industrial Shields boards package index. Wikipedia: RS-485 (termination at the ends, typical 120 Ω impedance, A and B naming).

Tutorial paso a paso para montar un master y un slave Modbus RTU por RS-485 con dos ESP32 PLC y la librería Modbus de Industrial Shields.

Commenting is not enabled on this course.