Modbus RTU sensor over RS-485 (MAX485)
Poll an industrial temperature and humidity sensor with Modbus RTU through a MAX485 transceiver.
Communication · Intermediate
In a real product: Building management system (Industrial): Polls temperature and humidity sensors over Modbus.
Factories, buildings and solar plants wire their sensors on RS-485, and most of them speak Modbus RTU. With a MAX485 module an Arduino becomes a Modbus master that asks each sensor for its readings in turn.
What you'll learn
- How RS-485 sends a UART over a differential pair, one talker at a time
- Switching a half-duplex transceiver between sending and listening
- A Modbus request and reply: slave address, function code, registers and CRC
How it works
The MAX485 turns the board's serial TX into a difference between the A and B wires, and the bus back into RX. Only one device may drive the pair at once, so its DE and RE pins (tied together, on pin 4) are HIGH while the board sends and LOW while it listens. ModbusMaster switches them in its preTransmission() and postTransmission() callbacks.
readInputRegisters(1, 2) sends slave address 1, function 0x04, start register 1 and a count of 2, then a CRC-16. The sensor answers with the two registers: temperature and humidity in tenths. SoftwareSerial on pins 2 and 3 carries the bus, so the serial monitor keeps pins 0 and 1.
Try this
- Click the sensor while it runs and change the temperature and humidity.
- Set the sensor's address to 2: the sketch gets error E2 (a time-out) until you ask address 2.
- Remove the
postTransmissioncallback: the board keeps driving the bus and never hears the reply.
sketch.ino
// A Modbus RTU master on RS-485: MAX485 RO on 2, DI on 3, DE and RE on 4. Reads the sensor at address 1 every second.
#include <SoftwareSerial.h>
#include <ModbusMaster.h>
const int RX = 2, TX = 3, DE_RE = 4;
SoftwareSerial rs485(RX, TX);
ModbusMaster sensor;
void preTransmission() { digitalWrite(DE_RE, HIGH); } // drive the bus
void postTransmission() { digitalWrite(DE_RE, LOW); } // listen for the reply
void setup() {
Serial.begin(9600);
pinMode(DE_RE, OUTPUT);
digitalWrite(DE_RE, LOW);
rs485.begin(9600);
sensor.begin(1, rs485);
sensor.preTransmission(preTransmission);
sensor.postTransmission(postTransmission);
}
void loop() {
uint8_t result = sensor.readInputRegisters(1, 2);
if (result == sensor.ku8MBSuccess) {
float celsius = (int16_t)sensor.getResponseBuffer(0) / 10.0;
float humidity = sensor.getResponseBuffer(1) / 10.0;
Serial.print("Temperature ");
Serial.print(celsius, 1);
Serial.print(" C Humidity ");
Serial.print(humidity, 1);
Serial.println(" %");
} else {
Serial.print("Modbus error 0x");
Serial.println(result, HEX);
}
delay(1000);
}