Projects / Read Modbus sensors with an ESP32

Read Modbus sensors with an ESP32

Intermediate3 hGuided buildReviewed

Build it step by step

0 of 6 done
  1. ESP32LM2596

    Set the converter

    Trim the LM2596 to 5.0 V with a multimeter.

  2. ESP32

    Wire the bus

    Connect A to A and B to B between the module and the sensor.

  3. ESP32

    Check the sensor settings

    Read its datasheet for address, baud rate and register map.

  4. ESP32

    Read once

    Upload the sketch and watch the Serial Monitor print N, P and K.

  5. ESP32

    Add MQTT

    Put your broker details in and subscribe on another device.

  6. ESP32

    Scale and label

    Convert the raw integers to the units in the datasheet.

In short

How do you build a read Modbus sensors with an ESP32?

An ESP32 reads an RS-485 Modbus sensor such as a soil NPK probe and publishes it over MQTT. You need ESP32 DevKit V1, RS485 to TTL auto-direction module, NPK soil sensor (RS485), 12 V 2 A DC adapter and LM2596 Buck Module. It takes 6 steps and about 180 minutes.

Level
Intermediate
Time
About 180 min
Parts
5

Parts list

Tick what you already own. It saves to My Garage, so “Build with what I have” knows.

Wiring

FromToWhy
12 V adapter +LM2596 IN+ and NPK sensor power +Supply
12 V adapter -LM2596 IN-, sensor power - and ESP32 GNDCommon ground
LM2596 OUT+ (set to 5.0 V first)ESP32 VIN and RS-485 module VCCRegulated 5 V
RS-485 module TXD (or DI)ESP32 GPIO17 (TX2)Data to the bus
RS-485 module RXD (or RO)ESP32 GPIO16 (RX2)Data from the bus
RS-485 module ASensor A (often yellow)Bus A
RS-485 module BSensor B (often blue)Bus B

Code

Arduino IDE with the ESP32 boards package, board "ESP32 Dev Module". Install "ModbusMaster" by Doc Walker and "PubSubClient" by Nick O'Leary. Register addresses, baud rate and slave address differ between probes: 0x001E to 0x0020 for N, P, K and 4800 baud are common, so check your sensor's own table. Put your own Wi-Fi, broker and MQTT details in the placeholders. Set the LM2596 to exactly 5.0 V on a multimeter before connecting the ESP32, and do not feed 12 V to the ESP32. Treat raw NPK probe values as indicative, since they are not a laboratory soil test.

Runs on a virtual ESP32 Dev Module in your browser, with sliders for the sensors. Happy with it? Verify and upload to your real board from the same page (Chrome or Edge on a computer).

#include <WiFi.h>
#include <PubSubClient.h>
#include <ModbusMaster.h>

const char* WIFI_NAME = "YOUR_WIFI_NAME";
const char* WIFI_PASSWORD = "YOUR_WIFI_PASSWORD";
const char* MQTT_HOST = "YOUR_BROKER_ADDRESS";
const char* MQTT_USER = "YOUR_MQTT_USER";
const char* MQTT_PASS = "YOUR_MQTT_PASSWORD";

WiFiClient net;
PubSubClient mqtt(net);
ModbusMaster node;

void setup() {
  Serial.begin(115200);
  Serial2.begin(4800, SERIAL_8N1, 16, 17);   // many NPK probes use 4800 baud; check your sensor sheet
  node.begin(1, Serial2);                    // slave address 1
  WiFi.begin(WIFI_NAME, WIFI_PASSWORD);
  while (WiFi.status() != WL_CONNECTED) delay(500);
  mqtt.setServer(MQTT_HOST, 1883);
}

void loop() {
  if (!mqtt.connected()) mqtt.connect("modbus-esp32", MQTT_USER, MQTT_PASS);
  uint8_t result = node.readHoldingRegisters(0x001E, 3);   // nitrogen, phosphorus, potassium
  if (result == node.ku8MBSuccess) {                       // the library checks the CRC for you
    int n = node.getResponseBuffer(0), p = node.getResponseBuffer(1), k = node.getResponseBuffer(2);
    Serial.printf("N %d P %d K %d mg/kg\n", n, p, k);
    char msg[64];
    snprintf(msg, sizeof msg, "{\"n\":%d,\"p\":%d,\"k\":%d}", n, p, k);
    mqtt.publish("farm/field1/npk", msg);
  } else {
    Serial.printf("Modbus error 0x%02X\n", result);
  }
  mqtt.loop();
  delay(60000);                                            // once a minute
}

What the serial monitor should show

Open the serial monitor at the baud rate in the code. This is what our simulator prints for a virtual ESP32 Dev Module with its sensors at their default values. Your numbers will follow your real readings, but the format should match.

Modbus error 0x00

Test checklist

What you should see at each check. If a reading is far off, stop and use the troubleshooting list.

CheckExpected
Probe in airLow or zero readings
Probe in moist soilReadings rise
Wrong baud rateModbus error printed
Subscribe on the brokerJSON message once a minute

If it does not work

Modbus error 0xE2

Timeout. Check A and B, power to the sensor and the baud rate.

Values are always 0

The probe needs to be in soil and warmed up.

Swapped A and B gives silence

Swap the two bus wires.

MQTT never connects

Check the broker address, user and password.

Still stuck? Find the fault step by step with your multimeter →

Ask Lark AI

Common questions

What parts do I need for the read Modbus sensors with an ESP32?

ESP32 DevKit V1, RS485 to TTL auto-direction module, NPK soil sensor (RS485), 12 V 2 A DC adapter and LM2596 Buck Module.

How long does the read Modbus sensors with an ESP32 take to build?

About 180 minutes for a intermediate maker, in 6 steps.

How do I know the read Modbus sensors with an ESP32 works?

Probe in air: Low or zero readings. Probe in moist soil: Readings rise. Wrong baud rate: Modbus error printed.

Modbus error 0xE2: what should I check?

Timeout. Check A and B, power to the sensor and the baud rate.

Values are always 0: what should I check?

The probe needs to be in soil and warmed up.

Swapped A and B gives silence: what should I check?

Swap the two bus wires.

MQTT never connects: what should I check?

Check the broker address, user and password.