Components · 9 min read

MAX485 Arduino Modbus RTU: RS485 Wiring, DE/RE and Code

MAX485 Arduino Modbus guide: RS485 wiring, DE/RE direction control, 120 Ω termination, Modbus RTU frames, function codes, plus ESP32 and Pico code.

To use Modbus with a MAX485 and Arduino, all you need is a small transceiver module. It turns Arduino's UART signal into a two-wire RS485 line that is noise-resistant and can run up to 1200 metres. The language spoken on that line is usually Modbus RTU: industrial temperature and humidity sensors, energy meters, solar inverters, motor drives and PLCs use it to share data held in 16-bit boxes called registers.

In this article you'll first see why RS485 works over such long distances, the MAX485's pins, and the most common source of trouble: DE/RE direction control. Then we'll take a Modbus RTU frame apart byte by byte, CRC included, check the line with a library-free test sketch and read registers with the ModbusMaster library on Arduino Uno, ESP32 and Raspberry Pi Pico. If serial communication is new to you, take a look at the UART serial communication article first.

What is RS485 and how does it work?

In plain UART, one wire carries 0 or 5 V relative to GND; the longer the cable, the more noise and voltage drop spoil that signal. RS485 works differentially: information is carried by the difference between two wires called A and B. The receiver only looks at that difference and can read one as small as about 200 mV correctly. Interference from outside lands on both wires at the same time, so the difference stays the same and the signal survives; twisting the two wires together (twisted pair) makes this effect even stronger. The line is half duplex: the same two wires are used to send and receive, but only one device may talk at a time. The standard defines 32 "unit loads" per line; a transceiver like the MAX485 counts as one unit load.

FeatureUART (TTL)RS232RS485
SignalSingle-ended, 0/5 V or 0/3.3 VSingle-ended, about ±3–15 VDifferential, A-B difference
Approx. max cable lengthA few metresAround 15 m1200 m
Number of devices2232 unit loads (more with 1/8-load chips)
WiresTX, RX, GNDTX, RX, GNDA, B and a recommended GND
DirectionFull duplexFull duplexHalf duplex (2-wire)
Typical useOn-board, modulesOld PC portsFactories, energy, building automation

The MAX485 module: pins and specifications

PinJobConnect to
RO (Receiver Output)Data received from the lineThe board's RX pin
RE (Receiver Enable, active low)Receiver on while LOWTied to DE, to one digital pin
DE (Driver Enable)Driver drives the line while HIGHTogether with RE on the same pin
DI (Driver Input)Data to send onto the lineThe board's TX pin
VCC / GND5 V supply5V and GND
A / BDifferential lineA and B of the other devices

According to its datasheet, the MAX485 runs on 4.75–5.25 V, carries data at up to 2.5 megabits per second and appears as one unit load on the line. Most of the blue modules on the market have a 120 Ω termination resistor soldered between A and B (a small SMD part usually marked "121") and pull-up/pull-down resistors that hold the idle line at a defined level. That's handy, but it can cause trouble on devices in the middle of the line; you'll see why below.

Direction control with DE and RE

Because the line is half duplex, Arduino has to tell the MAX485 "I'm talking now" or "I'm listening now". When DE is HIGH the driver drives the line; RE is active low, so the receiver works when it's LOW. If you solder these two pins together and connect them to one digital pin, a single command switches direction: HIGH = transmit, LOW = listen. Timing is the critical part. You must pull the pin LOW after the last bit of the last byte has left; pull it too early and you get no reply, or the other side sees a CRC error. Leave it too late and you miss the first bytes of the device's reply. On a hardware serial port you use Serial.flush() for this, because it waits until transmission has completely finished; the ModbusMaster library does that itself before calling postTransmission.

DEREStateWhen?
LOWLOWListen onlyIdle and receiving replies
HIGHHIGHTransmit onlyWhile sending a request
LOWHIGHReceiver and driver off, low powerLong idle periods (needs separate pins)
HIGHLOWTransmits and reads back its own dataDebugging, echo check

MAX485 wiring: Arduino Uno, ESP32 and Pico

Module pinArduino UnoESP32Raspberry Pi Pico
VCC5V3V3 (3.3 V module)3V3(OUT) (3.3 V module)
GNDGNDGNDGND
ROD10 (SoftwareSerial RX)GPIO 16 (Serial2 RX)GP1 (UART0 RX)
DID11 (SoftwareSerial TX)GPIO 17 (Serial2 TX)GP0 (UART0 TX)
DE + RE (tied)D2GPIO 4GP2
A / BLine wires A and BLine wires A and BLine wires A and B
A MAX485 powered from 5 V outputs 5 V on RO, which is too much for the 3.3 V pins of the ESP32 and Pico. Running the MAX485 on 3.3 V is outside its datasheet too; even if it sometimes works, it isn't reliable. For ESP32 and Pico, use a 3.3 V transceiver module such as the MAX3485 or SP3485, or keep the MAX485 on 5 V and pass RO through a logic level converter. Watch the labels too: some manufacturers call A the positive line, others the negative one. If you get no reply at all, swap A and B first.

Cable, 120 Ω termination and 1200 metres

  • Use twisted-pair cable: A and B must be in the same pair. One pair of an Ethernet cable works for short and medium runs; for long lines choose a shielded cable made for RS485.
  • Daisy chain, not star: Connect the devices one after another along a single line. Stubs from the main line to a device should be as short as possible; long stubs cause reflections.
  • Termination: Put 120 Ω between A and B at the two ends of the line only. If devices in the middle have a termination resistor, remove it or open its jumper; extra resistors weaken the signal.
  • Common reference: Even though it's differential, the ground difference between devices is limited (about -7 to +12 V). On long runs, join the GNDs with a third wire.
  • Speed and distance: As a rough rule, cable length (metres) times speed (bit/s) shouldn't exceed 10⁸: 1200 m is fine at 9600 baud, while at 1 Mbit/s you're down to about 100 m.
  • Idle line level (bias): If the line floats while nobody talks, receivers see garbage. The modules' pull-up/pull-down resistors fix this; one bias point on the line is enough.

What is Modbus RTU? The frame structure

Modbus is a question-and-answer protocol. There is one master on the line (called the client in newer documents) and only it asks questions; the slaves (servers) answer only questions sent to their own address. Each device has a unique address from 1 to 247; address 0 is broadcast, everyone listens but nobody replies. In RTU mode data travels as binary bytes, and silence marks the end of a frame: there must be a gap of at least 3.5 characters between two frames. At 9600 baud one character takes about 1.15 ms, so that gap is roughly 4 ms; above 19200 baud the standard recommends a fixed 1.75 ms. The serial settings must match on both sides: the standard's default is 8 data bits, even parity and 1 stop bit (8E1), but many sensors ship with 8N1.

FieldLengthExample requestMeaning
Address1 byte01Device address 1–247; 0 is broadcast
Function code1 byte03What is requested (e.g. read holding registers)
Data0–252 bytes00 00 00 02Start address (0x0000) and quantity (2)
CRC2 bytesC4 0BCRC-16 error check, low byte first

Modbus function codes

CodeNameWhat it does
01 (0x01)Read CoilsReads 1-bit outputs (such as relays)
02 (0x02)Read Discrete InputsReads 1-bit read-only inputs
03 (0x03)Read Holding RegistersReads 16-bit read/write registers; the most used code
04 (0x04)Read Input RegistersReads 16-bit read-only measurement registers
05 (0x05)Write Single CoilTurns a single bit on (FF00) or off (0000)
06 (0x06)Write Single RegisterWrites a 16-bit value to one register
15 (0x0F)Write Multiple CoilsWrites several bits at once
16 (0x10)Write Multiple RegistersWrites several registers at once

Byte-by-byte example: request, reply and error

Byte(s)ValueMeaning
101Address of the replying device
203Function code (same as the request)
304Number of data bytes that follow (2 registers × 2 bytes)
4–500 FARegister 1 = 250 → 25.0 °C with a 0.1 scale
6–701 C2Register 2 = 450 → 45.0 % humidity with a 0.1 scale
8–95A 03CRC-16 (low byte first)

Notice that the data bytes come big-endian (high byte first), but the CRC's low byte comes first; that difference is where most people trip up when writing their first Modbus code. If the device can't handle a request, it returns an exception response instead of a normal reply: the top bit of the function code is set and an error code follows. For example, asking for a register that doesn't exist gets you 01 83 02 C0 F1: 0x83 = 0x03 + 0x80, and 02 means "illegal data address". The other exception codes you'll meet are 01 (function not supported), 03 (illegal value) and 04 (device failure). Negative temperatures arrive in two's complement: read 0xFF9C as a signed 16-bit number and you get -100, i.e. -10.0 °C.

Register addresses: 40001 or 0?

Data typeManual notationRead codeWrite codeAddress in the frame
Coil (1 bit, read/write)00001–099990105, 15Notation − 1 (00001 → 0)
Discrete input (1 bit, read-only)10001–1999902NoneNotation − 10001
Input register (16 bit, read-only)30001–3999904NoneNotation − 30001
Holding register (16 bit, read/write)40001–499990306, 16Notation − 40001 (40108 → 107 = 0x006B)
The most common Modbus mistake is an address that's off by one. If the manual says "40001", you put 0 in the frame and in the code; the first digit only tells you the data type, the rest is a position counted from 1. Some manufacturers instead give the address directly as a hexadecimal number starting at 0 (e.g. 0x0000). If you get exception code 02, first try the address one lower or one higher, and check in the manual whether the register is read with 03 or 04.

A first test without a library (Arduino Uno)

Before moving to a library, use the sketch below to confirm the line really works. It builds the request from the table above together with its CRC, sends it through the MAX485, prints the reply in hexadecimal on the Serial Monitor and checks the CRC. The Uno's only hardware serial port is tied to USB, so the RS485 side uses SoftwareSerial; because SoftwareSerial also waits for the last bit when it sends a byte, it's safe to pull DE/RE LOW right after write().

C++ (Arduino IDE)
1// Kütüphanesiz Modbus RTU: 03 isteği gönder, cevabı HEX yazdır / Library-free Modbus RTU: send a 03 request, print the reply in HEX
2#include <SoftwareSerial.h>
3
4const int RS485_RX = 10;     // MAX485 RO
5const int RS485_TX = 11;     // MAX485 DI
6const int RS485_DIR = 2;     // MAX485 DE + RE birlikte / DE + RE tied together
7SoftwareSerial rs485(RS485_RX, RS485_TX);
8
9uint16_t crc16(const uint8_t *data, uint8_t len) {   // Modbus CRC-16 (polinom / polynomial 0xA001)
10  uint16_t crc = 0xFFFF;
11  for (uint8_t i = 0; i < len; i++) {
12    crc ^= data[i];
13    for (uint8_t b = 0; b < 8; b++) crc = (crc & 1) ? (crc >> 1) ^ 0xA001 : crc >> 1;
14  }
15  return crc;
16}
17
18void setup() {
19  Serial.begin(9600);
20  rs485.begin(9600);                 // cihazın baud hızı / the device's baud rate
21  pinMode(RS485_DIR, OUTPUT);
22  digitalWrite(RS485_DIR, LOW);      // varsayılan: dinle / default: listen
23}
24
25void loop() {
26  // Adres 1, fonksiyon 03, başlangıç 0x0000, 2 register / address 1, function 03, start 0x0000, 2 registers
27  uint8_t req[8] = { 0x01, 0x03, 0x00, 0x00, 0x00, 0x02, 0, 0 };
28  uint16_t crc = crc16(req, 6);
29  req[6] = crc & 0xFF;               // CRC önce düşük bayt / CRC low byte first
30  req[7] = crc >> 8;
31
32  digitalWrite(RS485_DIR, HIGH);     // gönder / transmit
33  rs485.write(req, sizeof(req));     // SoftwareSerial son bit bitince döner / returns after the last bit
34  digitalWrite(RS485_DIR, LOW);      // hemen dinlemeye geç / switch back to listen at once
35
36  uint8_t resp[32];
37  uint8_t n = 0;
38  unsigned long start = millis(), lastByte = 0;
39  while (millis() - start < 1000) {                  // en fazla 1 s bekle / wait at most 1 s
40    if (rs485.available()) {
41      if (n < sizeof(resp)) resp[n++] = rs485.read(); else rs485.read();
42      lastByte = millis();
43    } else if (n > 0 && millis() - lastByte > 5) {   // 5 ms sessizlik = çerçeve bitti / 5 ms silence = frame ended
44      break;
45    }
46  }
47
48  Serial.print(F("Cevap / Reply: "));
49  for (uint8_t i = 0; i < n; i++) {
50    if (resp[i] < 0x10) Serial.print('0');
51    Serial.print(resp[i], HEX);
52    Serial.print(' ');
53  }
54  Serial.println();
55
56  if (n < 5) {
57    Serial.println(F("Cevap yok: A/B, baud, adres? / No reply: A/B, baud, address?"));
58  } else if (crc16(resp, n - 2) != (uint16_t)(resp[n - 2] | (resp[n - 1] << 8))) {
59    Serial.println(F("CRC hatali / Bad CRC"));
60  } else if (resp[1] & 0x80) {
61    Serial.print(F("Istisna kodu / Exception code: "));
62    Serial.println(resp[2]);
63  } else if (resp[1] == 0x03 && resp[2] == 4) {
64    uint16_t r0 = (resp[3] << 8) | resp[4];          // veri büyük bayt önce / data is big-endian
65    uint16_t r1 = (resp[5] << 8) | resp[6];
66    Serial.print(F("Register 0: ")); Serial.println(r0);
67    Serial.print(F("Register 1: ")); Serial.println(r1);
68  }
69  delay(2000);
70}

Reading a sensor with ModbusMaster

  1. Open the Library Manager in the Arduino IDE, type ModbusMaster and install the library by Doc Walker. If installing libraries is new to you, the adding Arduino libraries article will help.
  2. From your device's manual, note its address, baud rate, parity and the address, type and scale of the registers you want to read.
  3. Change SLAVE_ID, REG_START, REG_COUNT and the rs485.begin() speed in the code to match.
  4. Upload the code and open the Serial Monitor at 9600 baud. If you see an error code instead of values, compare it with the table below and the common problems section.
C++ (Arduino IDE)
1// ModbusMaster ile sıcaklık-nem sensörü okuma (Arduino Uno) / Reading a temperature-humidity sensor with ModbusMaster (Arduino Uno)
2#include <ModbusMaster.h>
3#include <SoftwareSerial.h>
4
5const int RS485_DIR = 2;           // DE + RE
6SoftwareSerial rs485(10, 11);      // RX = RO, TX = DI
7ModbusMaster sensor;
8
9const uint8_t SLAVE_ID = 1;        // cihaz adresi / device address
10const uint16_t REG_START = 0x0000; // kılavuzdaki ilk register / first register from the manual
11const uint16_t REG_COUNT = 2;      // sıcaklık + nem / temperature + humidity
12
13void preTransmission()  { digitalWrite(RS485_DIR, HIGH); }   // göndermeden önce / before sending
14void postTransmission() { digitalWrite(RS485_DIR, LOW); }    // gönderdikten sonra / after sending
15
16void setup() {
17  pinMode(RS485_DIR, OUTPUT);
18  digitalWrite(RS485_DIR, LOW);
19  Serial.begin(9600);
20  rs485.begin(9600);
21  sensor.begin(SLAVE_ID, rs485);
22  sensor.preTransmission(preTransmission);
23  sensor.postTransmission(postTransmission);
24}
25
26void loop() {
27  uint8_t result = sensor.readHoldingRegisters(REG_START, REG_COUNT);   // fonksiyon 03 / function 03
28  if (result == sensor.ku8MBSuccess) {
29    float temperature = (int16_t)sensor.getResponseBuffer(0) / 10.0;  // eksi değer olabilir, ölçek 0,1 / may be negative, scale 0.1
30    float humidity = sensor.getResponseBuffer(1) / 10.0;
31    Serial.print(F("Sicaklik / Temp: ")); Serial.print(temperature, 1);
32    Serial.print(F(" C  Nem / Hum: "));   Serial.print(humidity, 1);
33    Serial.println(F(" %"));
34  } else if (result == sensor.ku8MBResponseTimedOut) {
35    Serial.println(F("Zaman asimi: kablo, A/B, baud / Timeout: wiring, A/B, baud"));
36  } else {
37    Serial.print(F("Modbus hatasi / Modbus error: 0x"));
38    Serial.println(result, HEX);
39  }
40  delay(2000);
41}
ModbusMaster functionModbus codeNote
readCoils(address, qty)01Bits arrive packed in getResponseBuffer()
readDiscreteInputs(address, qty)02Read-only bits
readHoldingRegisters(address, qty)03The standard allows 125 registers; the library's buffer is smaller, so split large blocks
readInputRegisters(address, qty)04Measurements usually live here
writeSingleCoil(address, state)05For example switching a relay
writeSingleRegister(address, value)06Changing a setting, e.g. a target temperature
writeMultipleRegisters(address, qty)16Fill it first with setTransmitBuffer(i, value)
Return value–0x00 success, 0x01–0x04 exception, 0xE2 timeout, 0xE3 CRC error

Reading inverters and energy meters with an ESP32

The ESP32's second hardware serial port (Serial2) can be mapped to any pins, which makes it ideal for RS485; you can also send the readings over Wi-Fi straight to Home Assistant via MQTT. Solar inverters and energy meters often use values that don't fit in one register: voltage, power or total energy sit in two consecutive registers as a 32-bit integer or a 32-bit float. Which register is the high word (the word order) varies by manufacturer; if a value looks absurd, swap the two words. For integer registers, watch the scale in the manual: 2305 with a 0.1 scale means 230.5 V. There are also "auto-direction" RS485 modules without a DE/RE pin that switch direction by themselves; with those you don't need preTransmission and postTransmission.

C++ (Arduino IDE)
1// ESP32 + 3,3 V RS485 modülü: 32 bit float ve tamsayı register okuma / ESP32 + 3.3 V RS485 module: reading 32-bit float and integer registers
2#include <ModbusMaster.h>
3
4const int RS485_RX = 16;           // modül RO / module RO
5const int RS485_TX = 17;           // modül DI / module DI
6const int RS485_DIR = 4;           // DE + RE
7ModbusMaster meter;
8
9const uint16_t REG_FLOAT = 0x0000; // ör. gerilim, 2 register float (kılavuzdan) / e.g. voltage, 2-register float (from the manual)
10const uint16_t REG_INT = 0x0010;   // ör. durum kodu, 1 register (kılavuzdan) / e.g. status code, 1 register (from the manual)
11
12void preTransmission()  { digitalWrite(RS485_DIR, HIGH); }
13void postTransmission() { digitalWrite(RS485_DIR, LOW); }
14
15// İki 16 bit register'ı float'a çevir (önce yüksek word) / combine two 16-bit registers into a float (high word first)
16float wordsToFloat(uint16_t hi, uint16_t lo) {
17  uint32_t raw = ((uint32_t)hi << 16) | lo;
18  float f;
19  memcpy(&f, &raw, sizeof(f));
20  return f;
21}
22
23void setup() {
24  Serial.begin(115200);
25  pinMode(RS485_DIR, OUTPUT);
26  digitalWrite(RS485_DIR, LOW);
27  Serial2.begin(9600, SERIAL_8N1, RS485_RX, RS485_TX);   // cihazın ayarıyla aynı / same as the device setting
28  meter.begin(1, Serial2);
29  meter.preTransmission(preTransmission);
30  meter.postTransmission(postTransmission);
31}
32
33void loop() {
34  uint8_t r = meter.readInputRegisters(REG_FLOAT, 2);    // fonksiyon 04 / function 04
35  if (r == meter.ku8MBSuccess) {
36    float value = wordsToFloat(meter.getResponseBuffer(0), meter.getResponseBuffer(1));
37    // Saçma çıkarsa word sırası ters olabilir / if it looks absurd, the word order may be swapped
38    Serial.print(F("Float: ")); Serial.println(value, 2);
39  } else {
40    Serial.print(F("Hata / Error 0x")); Serial.println(r, HEX);
41  }
42
43  delay(50);                                             // istekler arası kısa ara / short gap between requests
44  r = meter.readHoldingRegisters(REG_INT, 1);            // fonksiyon 03 / function 03
45  if (r == meter.ku8MBSuccess) {
46    Serial.print(F("Durum / Status: ")); Serial.println(meter.getResponseBuffer(0));
47  }
48  delay(2000);
49}

Modbus RTU with Raspberry Pi Pico (MicroPython)

On the Pico you can build the frame you've just learned directly in Python, without relying on a ready-made library. The code below calculates the CRC, keeps DE/RE HIGH for the transmission time, collects the reply, checks CRC and exceptions and returns the registers as a list. The transmission time is calculated from the baud rate: at 9600 baud an 8-byte request takes about 8.3 ms. If MicroPython is new to you, start with the MicroPython basics article.

MicroPython
1# Raspberry Pi Pico (MicroPython) + 3,3 V RS485 modülü: Modbus RTU 03 okuma
2# Raspberry Pi Pico (MicroPython) + 3.3 V RS485 module: Modbus RTU function 03 read
3from machine import UART, Pin
4import time
5
6BAUD = 9600
7uart = UART(0, baudrate=BAUD, tx=Pin(0), rx=Pin(1))   # GP0 = DI, GP1 = RO
8de_re = Pin(2, Pin.OUT, value=0)                      # DE + RE, 0 = dinle / 0 = listen
9
10def crc16(data):                                      # Modbus CRC-16
11    crc = 0xFFFF
12    for b in data:
13        crc ^= b
14        for _ in range(8):
15            crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
16    return crc
17
18def read_holding(slave, start, count):
19    frame = bytearray([slave, 0x03, start >> 8, start & 0xFF, count >> 8, count & 0xFF])
20    crc = crc16(frame)
21    frame += bytes([crc & 0xFF, crc >> 8])            # önce düşük bayt / low byte first
22    while uart.any():                                 # eski baytları temizle / drop stale bytes
23        uart.read()
24    de_re.value(1)
25    uart.write(frame)
26    time.sleep_us(len(frame) * 10 * 1_000_000 // BAUD + 300)   # baytlar hatta çıkana kadar / until all bits are out
27    de_re.value(0)
28    resp = b""
29    deadline = time.ticks_add(time.ticks_ms(), 1000)
30    while time.ticks_diff(deadline, time.ticks_ms()) > 0:
31        if uart.any():
32            resp += uart.read()
33            time.sleep_ms(5)                          # kalan baytlar için kısa bekleme / short wait for the rest
34            if not uart.any():
35                break
36    if len(resp) < 5 or crc16(resp[:-2]) != resp[-2] | (resp[-1] << 8):
37        return None                                   # cevap yok ya da CRC hatalı / no reply or bad CRC
38    if resp[1] & 0x80:
39        print("Istisna / Exception:", resp[2])
40        return None
41    return [(resp[3 + 2 * i] << 8) | resp[4 + 2 * i] for i in range(resp[2] // 2)]
42
43while True:
44    regs = read_holding(1, 0x0000, 2)
45    if regs:
46        temp = (regs[0] - 65536 if regs[0] > 32767 else regs[0]) / 10   # işaretli değer / signed value
47        print("Sicaklik / Temp:", temp, "C  Nem / Hum:", regs[1] / 10, "%")
48    else:
49        print("Cevap yok / No reply")
50    time.sleep(2)

RS485 and Modbus project ideas

  • Idea: Place RS485 temperature and humidity sensors in different corners of a greenhouse and read them over a single cable; combine it with the smart greenhouse project article.
  • Idea: Read your solar inverter's output with an ESP32 and draw a daily chart in Home Assistant.
  • Idea: Monitor home energy use; the PZEM-004T v3 actually speaks Modbus RTU at TTL level and can be read with the same code.
  • Idea: Control a well pump at the far end of the garden, hundreds of metres away, with an Arduino and a relay over Modbus.
  • Idea: Link two Arduinos with RS485 and make one of them act as a Modbus slave you wrote yourself.
  • Idea: Feed the readings straight into a dashboard with ESPHome's Modbus support; start with setting up ESPHome.

Common problems and fixes

SymptomLikely causeFix
No reply at all (0xE2 timeout)A/B swapped, baud or parity mismatch, wrong addressSwap A and B, check 8N1/8E1, confirm the device address
Reply arrives but CRC error (0xE3)DE/RE goes LOW too early, no termination, no common GNDGo LOW after flush(), add 120 Ω at the ends, connect a GND wire
Exception code 02Register address off by one or wrong data typeTry the address minus or plus 1, try 04 instead of 03
Exception code 01The device doesn't support this functionUse the function code from the manual
Values absurdly large or smallWrong scale, sign or word orderApply the scale, cast to int16_t, swap the two words
The first request works, later ones failRequests too frequent, the device can't keep upWait at least a few tens of milliseconds between requests
ESP32 RX pin gets hot or diedRO of a 5 V MAX485 connected directlyUse a 3.3 V MAX3485/SP3485 module or a level converter
When you connect a new device, try it on a computer first: confirm its address, speed and registers with a cheap USB-RS485 adapter and a free Modbus test program. If the device answers the computer but not the Arduino, the problem is in the wiring or the DE/RE timing, which halves the search.

RS485 and Modbus may look industrial and complicated at first, but at heart they're just two wires, a direction pin and a simple question-and-answer routine. To strengthen the serial basics, follow the "Two Arduinos, One-Way Communication" and "Two Arduinos, Two-Way Communication" projects in the BlueGrays app step by step with circuit diagrams and code, then stretch the same idea to hundreds of metres with a MAX485.

Frequently asked questions

What is the difference between RS485 and Modbus?

RS485 is the physical layer: it defines how the signal travels over two wires, the voltage levels and the cabling rules. Modbus is the language spoken on that line; it defines frames made of an address, function code, data and CRC. Other protocols can run over RS485, and Modbus can also run over Ethernet as Modbus TCP.

How do I connect the MAX485 DE and RE pins?

The most common method is to tie DE and RE together and run them to a single digital pin. With the pin HIGH the module transmits; with it LOW it listens. Pull the pin LOW only after the last bit of the last byte has fully gone out; on a hardware serial port use Serial.flush() for that.

Do I need an RS485 termination resistor?

Short lines at low speeds may work without termination, but on long cables reflections corrupt the data. The right way is 120 Ω between A and B at the two ends of the line only. Devices in the middle should have no termination resistor.

Can I use a MAX485 with an ESP32?

You can, but a MAX485 powered from 5 V outputs 5 V on RO, and ESP32 pins aren't 5 V tolerant. The cleanest solution is a 3.3 V module such as the MAX3485 or SP3485. If you want to stay with the MAX485, put a level converter or a voltage divider on the RO line.

How many devices can I connect to one RS485 line?

The standard defines 32 unit loads per line; since a MAX485 is one unit load, you can connect 32 devices. With transceivers designed as quarter or eighth loads, that rises to 128 or 256. The Modbus address range itself is limited to 1–247.

Why is Modbus address 40001 written as 0 in code?

40001 is a notation: the first digit (4) says it's a holding register, the rest is a position counted from 1. The real address in the frame starts at 0, so 40001 becomes 0 in code and 40010 becomes 9. If the manual already gives the address in hex such as 0x0000, you don't subtract anything.

See all projects
One-Way Communication Between 2 Arduinos
AR-57Intermediate
Premium

One-Way Communication Between 2 Arduinos

You get two Arduinos talking over a single wire: press the button on one and the LED on the other lights up, press it again and it goes off.

4.5(38)
51
Two-Way Communication Between 2 Arduinos
AR-58Intermediate
Premium

Two-Way Communication Between 2 Arduinos

Two Arduinos are wired together and talk to each other: press the button on one and the light on the other comes on, press it again and it goes off.

4.5(20)
26
Temperature and Humidity with DHT11
AR-55Intermediate

Temperature and Humidity with DHT11

How warm is your room, and is the air humid or dry? The DHT11 sensor measures temperature and humidity, and the Arduino writes the values on a two-line LCD screen, refreshing every couple of seconds.

4.7(47)
96
HC-SR04 Distance Measurement (Serial Display)
AR-27Beginner

HC-SR04 Distance Measurement (Serial Display)

The HC-SR04 sensor works just like a bat finding its way in the dark: it sends out a sound you cannot hear, listens for the echo and measures how far away the object in front of it is.

4.6(52)
94
ESP32 DHT22 Temperature and Humidity (with LCD Display)
ES-15Intermediate

ESP32 DHT22 Temperature and Humidity (with LCD Display)

This project measures ambient temperature and humidity using a DHT22 sensor and displays the data in real time on a 16x2 I2C LCD. Data is read from the sensor using the one-wire protocol via the Adafruit DHT library. This project serves as the foundation for IoT weather stations, smart home automation, or environmental monitoring systems in greenhouses. Communication with the DHT22 is established via the ESP32's GPIO 4 pin.

4.8(38)
57
ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)
ES-40Advanced
Premium

ESP32 Temperature Data Logger (DHT22 + DS1307 RTC + microSD + OLED)

Build a timed temperature and humidity logger with the ESP32! A DHT22 sensor reads temperature and humidity once a minute, and each reading is saved to a microSD card in CSV format with a real-time stamp from the DS1307 RTC module. The OLED display shows the latest temperature, humidity, timestamp and total number of records live, in large text.

4.7(7)
12
ESP32 Wi-Fi STA Connection (with LCD Screen)
ES-25Advanced

ESP32 Wi-Fi STA Connection (with LCD Screen)

In this project, we connect the ESP32 to the home Wi-Fi network in Station (STA) mode in a secure, fault-tolerant manner. We store the SSID and password in a separate secrets.h file to prevent leaking to Git, set up an auto-reconnect mechanism, and display the RSSI signal level and IP address on an I2C LCD screen. The internal LED works as a status indicator. It is a production-grade connection manager.

4.4(21)
40
ESP32 Asynchronous Web Server (with IP Display on LCD)
ES-27Advanced

ESP32 Asynchronous Web Server (with IP Display on LCD)

In this project, we’re turning the ESP32 into an asynchronous web server that you can control from your phone or computer on the same Wi-Fi network. Thanks to the ESPAsyncWebServer library, the server can process multiple requests simultaneously (unlike the classic WebServer.h, which blocks on a single request). You’ll be able to open the ESP32’s IP address in a browser and click the ON/OFF buttons (the /on and /off routes) to turn the LED connected to GPIO 5 on and off.

4.8(16)
27