What is Modbus RTU? Read Sensor Data with Arduino Modbus RTU

What is Modbus RTU Read Sensor Data with Arduino Modbus RTU What is Modbus RTU Read Sensor Data with Arduino Modbus RTU

In today’s industrial landscape, efficient and reliable communication protocols are vital for automation, monitoring, and control. Modbus RTU stands out as a proven, industry-standard protocol that connects various devices—from sensors and actuators to controllers and computers—with ease. In this comprehensive guide, we will delve into every aspect of Modbus RTU, including its history, technical details, variations, and practical implementation using Arduino and RS485. Additionally, we will explore the indispensable MAX485 module, which plays a key role in ensuring robust RS485 communication.

Overview of Modbus RTU

In this tutorial, we explore the Modbus RTU protocol—a variant of the Modbus communication standard that uses binary coding and serial transmission. We will demonstrate how to implement it with Arduino to read sensor data from a slave device over an RS485 network. Our example centers on a humidity and temperature sensor operating on the Modbus RTU protocol. By writing custom Arduino code and interfacing through RS-485, you can efficiently retrieve and manage sensor data in real time.


What is Modbus?

What is Modbus protocol

Modbus is a serial communication protocol that was developed in 1979 by Modicon for use with programmable logic controllers (PLCs). Over the years, it has evolved into a de facto standard in industrial automation because of its simplicity, openness, and low-cost implementation. Key aspects of Modbus include:

  • Industrial Connectivity: Designed to connect industrial electronic devices such as sensors, instruments, actuators, and HMIs (Human Machine Interfaces).
  • Versatility: Ideal for monitoring and controlling field devices via computers and managing remote terminal units (RTUs) in applications such as gas and oil substations.
  • Binary Data Transmission: Data is transmitted in the form of binary bits (zeroes and ones), which correspond to positive and negative voltages. This binary format allows for rapid, efficient data transfer.

In a typical Modbus network, a single master device manages the communication with up to 247 slave devices, each assigned a unique address. The master not only reads data from these devices but also writes commands and configurations, ensuring coordinated operation across the network.


Variations of the Modbus Protocol

Modbus comes in several variations to suit different network environments and data transmission needs:

  1. Modbus ASCII:
    • Uses ASCII characters for data transmission.
    • Easier for debugging but less efficient compared to binary formats.
  2. Modbus RTU (Remote Terminal Unit):
    • Employs binary coding for higher data transmission speed and efficiency.
    • Integrates robust error-checking mechanisms like CRC (Cyclic Redundancy Check) to maintain data integrity.
  3. Modbus TCP/IP:
    • Designed for Ethernet networks.
    • Utilizes standard network infrastructure for communication, making it ideal for modern industrial IoT applications.

Each variant is tailored to specific operational requirements, with Modbus RTU being the preferred choice for serial communications in industrial environments.


Deep Dive into Modbus RTU

Modbus RTU is a specialized version of the Modbus protocol that facilitates efficient serial communication using binary data encoding. Here’s what sets it apart:

  • High-Speed Data Transmission:
    Modbus RTU employs binary coding, ensuring that data is transmitted quickly and efficiently between devices.
  • Robust Error Checking:
    A built-in CRC mechanism ensures the integrity of transmitted data, preventing corruption across the physical network.
  • Point-to-Point Communication:
    Typically, a single master device communicates with one or more slave devices. This architecture supports networks with up to 247 slave devices, each with a unique address.
  • Limited Communication Range:
    Often used in environments where devices are spread over distances up to 15 meters, making it ideal for building management and industrial automation systems.
  • Strict Mode Compatibility:
    Devices configured for Modbus RTU cannot interact with those using other modes (e.g., ASCII). For example, a device set for ASCII communication will not interpret data sent in RTU binary format.

Understanding RS-485 Interfaces and Electrical Standards

Modbus RTU is typically implemented over various serial interfaces, each suited to different distances and environments:

  • RS-232:
    • Ideal for short-distance communications, often used for direct connections between a device and a PC.
  • RS-485:
    • The most common interface for Modbus RTU.
    • Supports longer distances and the connection of multiple devices on a single bus network.
  • RS-422:
    • Similar to RS-485 but offers greater resistance to electrical noise, making it suitable for particularly harsh industrial environments.

These interfaces ensure that Modbus RTU can be deployed in a variety of settings, from small-scale setups to extensive industrial networks.


Technical Implementation: Slave IDs, Function Codes, and Data Packets

Modbus RTU

A key aspect of Modbus RTU is its meticulous organization of data communication. The technical implementation includes:

  • Slave IDs:
    • Each slave device is assigned a unique identifier, allowing the master to address and manage multiple devices simultaneously.
  • Function Codes:
    • Specific codes define the action to be performed (e.g., reading sensor data, writing data to a register).
    • These codes ensure that the communication is both precise and unambiguous.
  • Data Packets:
    • Data packets consist of addresses, data values, and checksums.
    • The checksum (CRC) is critical for validating the integrity of the data, ensuring that errors during transmission are detected and corrected.

This structured approach enables precise control and monitoring of networked devices, making Modbus RTU ideal for complex industrial systems.


The MAX485 Module for RS-485 Communication

Overview of the MAX485 IC

The MAX485 IC is a low-power transceiver designed specifically for RS-485 communication. Its robust design and ease of integration have made it a staple in both industrial and commercial applications for long-distance data transmission.

Types of MAX485 Modules

There are several types of MAX485 modules available on the market:

  1. Basic MAX485 Circuit Board: max485 ttl to rs485 converter module pinout diagram
    • Features input and output pins for direct interfacing.
    • In addition to the TX (transmit) and RX (receive) signals, you must control the RE (receiver enable) and DE (driver enable) pins manually.
  2. MAX485 Module with CD4069 Hex-Inverter IC:MAX485 with CD4069
    • This variant includes the CD4069 hex-inverter IC, which automatically drives the DE and RE pins.
    • Simplifies operation and programming by automatically switching between transmitting and receiving modes.

Key Features

  • Half-Duplex Communication:
    • Allows data to be transmitted and received over a single pair of wires (though not simultaneously).
    • This design supports efficient use of wiring while maintaining robust communication.
  • Driver and Receiver Control:
    • Includes dedicated driver enable and receiver enable pins, essential for controlling the mode of operation.
  • Unit Load (UL) Rating:
    • With a UL rating of 1, up to 32 MAX485 devices can be connected on a single RS-485 bus, enabling extensive network scalability.

By incorporating the MAX485 module, you ensure that your Arduino-based Modbus RTU system can handle long-distance, multi-device communication with high reliability.


RS485 Temperature and Humidity Sensor Overview

This sensor uses the standard Modbus RTU protocol, making it a reliable and cost-effective choice for monitoring temperature and humidity in various environments. By interfacing it with an Arduino and using RS-485 communication, you can quickly set up a system to collect sensor data and integrate it into larger control or data logging systems.

Industry Grade RS485 humidity and temperature sensor

Product Specifications

Before diving into the implementation, let’s review the sensor’s key specifications:

  • Power Supply: 5–30V DC
  • Maximum Power Consumption: ≤ 5W
  • Humidity Range: 0–100% RH
  • Temperature Range: -40° to 80° C
  • Accuracy:
    • Temperature: ± 0.3 °C
    • Humidity: ± 0.3% RH
  • Communication Protocol: Standard Modbus RTU
  • Communication Mode: RS485
  • Baud Rate Options:
    • Default: 9600 bps
    • Other supported rates: 1200, 2400, 4800, 9600, 19200 (configurable via software)
  • Default Equipment Address: 1 (modifiable from 1 to 254 by software)
  • Register Mapping:
    • Humidity: Address 0
    • Temperature: Address 1 (both software modifiable)
  • Wiring Mode:
    • Red: Positive (+)
    • Black: Ground (GND)
    • Yellow: A+
    • Green: B-

Communication Protocol Details

The sensor communicates using the Modbus RTU protocol. Understanding its communication parameters and data frame format is essential for successful integration.

Basic Communication Parameters

Parameter Specification
Coding 8-bit binary
Data Bits 8 bits
Parity Bit None
Stop Bit 1 bit
Error Checking CRC (Cyclic Redundancy Check)
Baud Rate 1200, 2400, 4800, 9600, 14400, 19200 bps (Factory default is 9600 bps)

Data Frame Format Definition

Each data frame transmitted between the sensor (slave) and the master (Arduino) follows this structure:

Component Specification
Initial Structure ≥ 4 bytes of time
Address Code 1 byte (Unique transmitter address, default 0x01)
Function Code 1 byte (For this sensor, only 0x03 is used to read register data)
Data Area N bytes (Specific communication data; note that the high byte is transmitted first for 16-bit data)
Error Check 16-bit CRC code (two bytes)
Time to End Structure ≥ 4 bytes of time
  • Address Code: Uniquely identifies the transmitter in the network (default is 0x01).
  • Function Code: This sensor uses function code 0x03 for reading register data.
  • Data Area: Contains the actual data from the registers. The humidity is read from register address 0 and temperature from address 1.
  • CRC Code: A two-byte checksum ensuring data integrity.

Looking for a Reliable PCB Manufacturer? PCBWay is the Best Choice!

Are you designing a product with custom PCBs but don’t know where to manufacture them? Whether you’re a hobbyist, engineer, or startup, getting high-quality PCBs made can be a challenge. PCBWay is the perfect solution for fast, affordable, and professional PCB manufacturing and assembly.

Why Choose PCBWay?

🚀 Fast & Affordable Prototyping – Need quick-turn PCB prototypes? PCBWay delivers high-quality boards with industry-leading turnaround times at cost-effective prices.

🔧 Advanced PCB Solutions – From HDI, High-frequency, Rigid-Flex, Thick Copper, and Metal Core PCBs, PCBWay supports all types of PCB technologies for even the most complex projects.

🛠️ Seamless PCB Assembly – Looking for a one-stop manufacturing solution? PCBWay provides SMT, Thru-hole, and Hybrid Assembly, ensuring your PCBs are assembled with precision.

💡 Instant Online Quoting – Upload your Gerber files and get an instant quote with real-time DFM (Design for Manufacturability) feedback to ensure your boards meet manufacturing standards.

📦 Real-time Order Tracking – Stay updated on every step of your order, from production to delivery, with full transparency.

🛎️ 24/7 Customer Support – Get one-on-one assistance via live chat anytime!

No Minimum Order Requirement – Order as few as 5 PCBs for small projects or prototyping.

Get Started Today!

Create an account on PCBWay and claim a $5 welcome bonus! Join thousands of engineers and makers who trust PCBWay for high-quality PCBs, reliable service, and competitive pricing.

👉 Order Now from PCBWay


Implementing Modbus RTU with Arduino and RS485 sensor

Another Example: Soil NPK Sensor with Arduino

Required components

Arduino NANO https://amzn.to/3jVNZON https://amzn.to/3KpUQry
MAX485 https://amzn.to/3hAFrbD https://amzn.to/3Ia8bTH
RS485 Temp& Humidity sensor https://amzn.to/4jPDTtd
Connecting Wires https://amzn.to/3H2BV4e https://amzn.to/3J0WVu2

Circuit diagram

Setting up the hardware correctly is vital for establishing reliable Modbus RTU communication. Below is the wiring diagram and connection details between the Arduino, MAX485 module, and RS485 humidity and temperature sensor.

Modbus RTU RS485 and MAX485 module with Arduino circuit diagram

Arduino to (MAX485 TTL to RS495)  Module Connections

  • VCC: Connect the MAX485 module’s VCC pin to the Arduino’s 5V pin.
  • GND: Connect the MAX485 module’s GND pin to one of the Arduino’s GND pins.
  • RO: Connect Arduino’s digital pin D10(RX) to the MAX485 module’s RO pin. enabling data reception from the MAX485 bus.
  • DI: Connect Arduino’s digital pin D11(TX) to the MAX485 module’s DI pin, This connection allows the Arduino to send data to the MAX485 bus.

In this code we are using SoftwareSerial library. The hardware TX/RX pins (D0 and D1) are tied to the USB-to-Serial converter on the Arduino Nano, which means they are used for communication with the computer via USB to send data to serial monitor. If you want to use other pins for serial communication (e.g., with a MAX485 module), SoftwareSerial is the way to go.

RS485 Sensor to (MAX485 TTL to RS495) Module Terminal Connections

  • A+ (Yellow Wire): Connect to the A+ terminal of your MAX485.
  • B- (Green Wire): Connect to the B- terminal of your MAX485.

Power Supply Connections for the RS485 sensor

  • Red Wire: Connect to a DC power supply between 5V and 30V.
  • Black Wire: Connect to the negative (ground) side of the power supply.

Code

For prototyping, you can use a breadboard and jumper wires. Finally, connect your Arduino to a computer via a USB cable to power the system and upload the code through Arduino IDE.

We need to install few libraries, which you can install through Arduino library manager or through below download links:

  • ModbusMaster – Download link
  • softwareserial – Built in Arduino IDE
//ModBus RTU communition example by circuitschools.com
#include <ModbusMaster.h>       // https://github.com/4-20ma/ModbusMaster
#include <SoftwareSerial.h>

// Define the pins for MAX485 control
#define MAX485_DE_PIN 2
#define MAX485_RE_PIN 3

// Create a SoftwareSerial object to communicate with the MAX485 module
SoftwareSerial mySerial(10, 11); // RX, TX

// Create a ModbusMaster object
ModbusMaster node;

// Function to set MAX485 in transmit mode
void preTransmission() {
  digitalWrite(MAX485_DE_PIN, HIGH); // Enable DE (Driver Enable)
  digitalWrite(MAX485_RE_PIN, HIGH); // Enable RE (Receiver Enable)
}

// Function to set MAX485 in receive mode
void postTransmission() {
  digitalWrite(MAX485_DE_PIN, LOW);  // Disable DE (Driver Enable)
  digitalWrite(MAX485_RE_PIN, LOW);  // Disable RE (Receiver Enable)
}

void setup() {
  // Initialize serial communication for debugging
  Serial.begin(9600);

  // Initialize SoftwareSerial for Modbus communication
  mySerial.begin(9600);

  // Set the DE and RE pins as outputs
  pinMode(MAX485_DE_PIN, OUTPUT);
  pinMode(MAX485_RE_PIN, OUTPUT);

  // Initialize Modbus communication with the Modbus slave ID 1
  node.begin(1, mySerial);

  // Attach the preTransmission and postTransmission functions
  node.preTransmission(preTransmission);
  node.postTransmission(postTransmission);

  // Allow some time for initialization
  delay(1000);
}

void loop() {
  uint8_t result;   // Variable to store the result of Modbus operations
  uint16_t data[2]; // Array to store the data read from the Modbus slave

  // Read 2 holding registers starting at address 0x0000
  result = node.readHoldingRegisters(0x0000, 2);

  // If the read is successful, process the data
  if (result == node.ku8MBSuccess) {
    // Get the response data from the response buffer
    data[0] = node.getResponseBuffer(0x00); // Humidity
    data[1] = node.getResponseBuffer(0x01); // Temperature

    // Calculate actual humidity and temperature values
    float humidity = data[0] / 10.0;      // Humidity is scaled by 10
    float temperature = data[1] / 10.0;   // Temperature is scaled by 10

    // Print the values to the Serial Monitor
    Serial.print("Humidity: ");
    Serial.print(humidity);
    Serial.println(" %RH");

    Serial.print("Temperature: ");
    Serial.print(temperature);
    Serial.println(" °C");
  } else {
    // Print an error message if the read fails
    Serial.print("Modbus read failed: ");
    Serial.println(result, HEX); // Print the error code in hexadecimal format
  }

  // Wait for 2 seconds before the next read
  delay(2000);
}

Example Output:

Once the code is uploaded to your Arduino, open the Serial Monitor (set to 9600 bps) to view the sensor readings. You should see output similar to:

Humidity: 45.6 %RH
Temperature: 23.4 °C

To verify the sensor’s responsiveness, try altering the environmental conditions around the sensor—such as heating it slightly or exposing it to moisture—and observe the changes in the recorded values.

Or, if there’s an error:

Modbus read failed: 0xE2

Code Explanation

  1. Setup:
    • Uses ModbusMaster library for Modbus communication.
    • Configures SoftwareSerial (pins 10-RX, 11-TX) and MAX485 control pins (DE=2, RE=3).
    • Initializes Modbus communication with slave device ID 1.
  2. RS485 Control:
    • Switches MAX485 to transmit/receive mode automatically before/after data transfer using preTransmission() (enable DE/RE) and postTransmission() (disable DE/RE).
  3. Main Loop:
    • Reads 2 holding registers (addresses 0x0000 and 0x0001) from the Modbus device.
    • Converts raw data to actual values:
      • Humidity = Register 0 ÷ 10 (%RH)
      • Temperature = Register 1 ÷ 10 (°C)
    • Prints values to Serial Monitor every 2 seconds or displays an error if reading fails.

Purpose: Reads and displays scaled temperature/humidity values from a Modbus sensor via RS485.

By following these steps, you can create a reliable system that leverages Modbus RTU for real-time monitoring and control.

Conclusion

This guide has walked you through every step required to integrate an RS485 Temperature and Humidity Sensor into your Arduino project using the standard Modbus RTU protocol. From understanding the product specifications and communication protocol details to wiring the hardware correctly and programming the Arduino with the ModbusMaster library, you now have a complete roadmap for reliable sensor data acquisition.

By following this guide, you can confidently deploy the sensor in a range of applications, whether for industrial automation, environmental monitoring, or building management systems. Embrace the robust and efficient communication offered by Modbus RTU, and transform your projects with accurate temperature and humidity readings.

Happy coding and innovating!

Add a comment

Leave a Reply

Your email address will not be published. Required fields are marked *