Try Embedded

RS-485 and Modbus

Differential multi-drop wiring, driver enable, and the Modbus RTU protocol.

The factory floor's serial bus

Industrial equipment (PLCs, energy meters, motor drives, sensors in a plant) is still widely connected with RS-485, and the protocol on top is usually Modbus RTU. Both are simple, robust over long cables in electrically noisy places, and decades old, which is exactly why they are everywhere.

RS-485: the physical layer

RS-485 is a UART signal driven differentially over a twisted pair:

PropertyValue
SignallingDifferential on A and B (sometimes labelled D− and D+; vendors disagree on which is which)
DistanceUp to about 1200 m at 100 kbit/s; shorter at higher rates
Nodes32 standard "unit loads"; 128 to 256 with fractional-load transceivers
TopologyOne daisy-chained bus (not a star), 120 Ω termination at both ends
DuplexUsually half duplex on one pair (two-wire); full duplex needs two pairs (four-wire)

Because many devices share one pair in half duplex, only one may drive the bus at a time. Each transceiver has a driver-enable (DE) input:

  1. Enable the driver.
  2. Send the bytes.
  3. Wait until the last stop bit has left the UART (the "transmission complete" flag, not "transmit buffer empty"), then disable the driver so others can answer.

Turning the driver off too early cuts the last byte; too late collides with the reply. Many MCUs drive DE automatically from the UART ("RS-485 mode", "driver enable" pin), which is the reliable option.

Failsafe biasing: when nobody drives, the bus floats and noise can look like a start bit. Bias resistors (or failsafe transceivers) hold the idle bus in a defined state.

Modbus RTU frames

Modbus is a request-response protocol: one master (client) asks, one addressed slave (server) answers.

| address (1) | function (1) | data (0-252) | CRC-16 (2, low byte first) |
  • Address 1 to 247; 0 is broadcast (no reply).
  • Frames are delimited by silence: at least 3.5 character times of idle line between frames; a gap of more than 1.5 characters inside a frame invalidates it. So the receiver must time gaps between bytes, typically with a timer restarted on every received byte (or the UART's receiver-timeout feature).
  • CRC-16/Modbus (polynomial 0xA001 reflected, initial value 0xFFFF) covers address, function and data.

The data model and common functions

TableAccessSizeRead functionWrite function
CoilsRead/write1 bit0x010x05 (single), 0x0F (multiple)
Discrete inputsRead-only1 bit0x02—
Input registersRead-only16 bits0x04—
Holding registersRead/write16 bits0x030x06 (single), 0x10 (multiple)

Registers are 16-bit and big-endian on the wire. Values wider than 16 bits (a 32-bit float or counter) span two registers, and word order is not standardised: check each device's manual.

Building a request

#include <stdio.h>
#include <stdint.h>

/* CRC-16/Modbus: reflected polynomial 0xA001, initial value 0xFFFF. */
static uint16_t crc16_modbus(const uint8_t *p, int n) {
  uint16_t crc = 0xFFFF;
  while (n--) {
    crc ^= *p++;
    for (int i = 0; i < 8; i++) crc = (crc & 1) ? (uint16_t)((crc >> 1) ^ 0xA001) : (uint16_t)(crc >> 1);
  }
  return crc;
}

int main(void) {
  /* Read 2 holding registers starting at address 0x006B from slave 17 */
  uint8_t req[8] = { 0x11, 0x03, 0x00, 0x6B, 0x00, 0x02 };
  uint16_t crc = crc16_modbus(req, 6);
  req[6] = (uint8_t)(crc & 0xFF);          /* CRC is sent low byte first */
  req[7] = (uint8_t)(crc >> 8);
  printf("request:");
  for (int i = 0; i < 8; i++) printf(" %02X", req[i]);
  printf("\n");

  /* A receiver checks a frame by running the CRC over everything including the CRC bytes: result 0. */
  printf("CRC over the whole frame: 0x%04X\n", crc16_modbus(req, 8));
  return 0;
}

Exceptions

A slave that cannot fulfil a request replies with the function code OR 0x80 and an exception code: 01 illegal function, 02 illegal data address, 03 illegal data value, 04 device failure. A master must also handle no reply at all with a timeout and retry.

Modbus TCP

The same data model and function codes over TCP port 502, with a 7-byte MBAP header (transaction id, protocol id, length, unit id) instead of the address and CRC. Gateways convert between Modbus TCP and RTU.

Other RS-485 protocols

PROFIBUS DP, BACnet MS/TP (building automation), DMX512 (stage lighting) and many proprietary protocols also run on RS-485. The physical-layer rules above apply to all of them.

Pitfall: Swapped A and B lines are the most common commissioning fault, made worse because manufacturers label them inconsistently. If a device never answers, swapping the pair is the first thing to try, after checking termination, baud rate, parity and the slave address.

Interview question: How would you implement a Modbus RTU slave on a microcontroller?

Answer: Receive bytes with UART interrupts or DMA, restarting a timer on each byte; when 3.5 character times pass with no byte (or the UART's receiver timeout fires), treat the buffer as a frame. Check length and CRC, ignore frames for other addresses, then decode the function code, validate the register range and values, and map them onto the device's data. Build the response or an exception response, append the CRC, enable the RS-485 driver, send, and release the driver on transmission complete. Respond within the master's timeout and handle broadcasts without replying.

Interview question: Why is RS-485 used in industrial environments instead of plain UART or RS-232?

Answer: Differential signalling rejects the common-mode noise picked up along long cables near motors and power wiring, allowing reliable communication over hundreds of metres to over a kilometre. It is multi-drop, so dozens of devices share one twisted pair, and transceivers tolerate a wide common-mode voltage range between distant grounds. RS-232 is single-ended, point-to-point and limited to about 15 metres.

Going deeper

Interview question: How would you read thirty energy meters along a 500 m cable in a factory?

Answer: RS-485 in a daisy chain with termination at both ends and biasing, Modbus RTU with each meter at its own address, polled in turn with timeouts and retries. Choose a baud rate that suits the cable length and polling rate, check every response's CRC, and mark a meter as offline after repeated failures without blocking the others.

Interview question: A 32-bit value read from a Modbus device looks like garbage. What do you check?

Answer: Word order. Modbus defines 16-bit registers as big-endian but says nothing about how two registers form a 32-bit value, so devices use either high word first or low word first, and some also swap bytes. Check the device manual, read a known value, and try swapping the two registers. Also confirm the register address offset (some documentation counts from 1, some from 0) and the data type.

Interview question: Why do both ends of an RS-485 bus need 120 Ω termination, and the middle nodes none?

Answer: The twisted pair is a transmission line with a characteristic impedance around 120 Ω. At an unterminated end the signal reflects back, causing ringing that can corrupt bits at higher rates or longer distances. A matching resistor at each physical end absorbs the signal. Terminating intermediate nodes as well would load the bus with several resistors in parallel, reducing the signal amplitude below what receivers need.

Explain it: In your own words, explain how a Modbus RTU master reads a register from a slave and how errors are detected.

Answer: The master sends a frame containing the slave's address, the function code for reading holding registers, the starting register address and the number of registers, followed by a CRC-16 of all of that. Only the addressed slave replies, with its address, the same function code, a byte count and the register values, plus its own CRC. The master checks the reply's CRC, that the address and function match, and that the reply arrived within its timeout. A set high bit in the function code means the slave returned an exception code instead, such as an illegal register address; a missing or corrupted reply leads to a retry.