BT San Technology

3 March 2026

Modbus RTU vs TCP: Where RS485 and Ethernet Fit

26 min read · Automation

Illustration: a PLC, a communication gateway and a network switch set up as a test rig
AI-generated illustration

The new power meter is installed. The manual says it supports Modbus. The electrician wires it to the RS485 port, sets up the polling program, and gets only a timeout, or a number that cannot be right, such as billions of units of accumulated energy. People often conclude the device is faulty. Most of the time the cause is wiring or register interpretation, and it can be fixed in a few minutes if you know what to look at.

This article separates three layers: the cable you use (RS485 or Ethernet), the language the devices speak (Modbus RTU or TCP), and the meaning of the data (the register map). It then shows the actual bytes of a read request in both TCP and RTU, using Python code that runs on a single machine with no device attached. Managers can read the problem section, the facts table and the checklist at the end. Technicians and programmers can follow the code step by step.

The real problem: the port is right, but the devices do not understand each other

Matching ports do not mean the devices can talk. RS485 is about the electrical signal on the wire (two differential lines). Ethernet is about the network. Modbus is the agreement on what to ask, what to answer, who starts, and what each number means. The same device may speak Modbus RTU over an RS485 cable or Modbus TCP over a LAN cable, and a gateway can translate between the two.

Three hypothetical situations, not projects of any BT San customer.

  • Six power meters on one RS485 line. Meters 1 to 4 read fine. Meters 5 and 6 drop out intermittently because the wiring branches out in a star and there is no terminating resistor, so the signal reflects. The higher the speed, the worse it gets.
  • A temperature sensor keeps answering 0. The program counts registers starting from 1, but the wire needs numbers starting from 0, so the read is off by one slot and returns a neighboring register instead.
  • The kWh value from a meter reads 8607918080 instead of 1234.5. A 32-bit float is stored in two registers, and the manufacturer put the upper half second, but the program assumed the upper half comes first. Nothing is broken. The word order just does not match.

These three cases separate by layer. The first is the cable layer. The second and third are the data-meaning layer. Working from the bottom layer up is faster than guessing, and it is the order used in the rest of this article.

Facts from the standard documents

TopicWhat the document saysEffect in practice
RTU frame formatA frame consists of a 1-byte slave number, the PDU (function code and data), and a 16-bit CRC sent low byte first. The sender must leave silence of at least 3.5 character times between frames, and a gap longer than 1.5 character times inside a frame makes the frame unusable. When the baud rate is above 19200, the spec fixes these at 750 microseconds and 1.75 milliseconds.A PC program that sends bytes in broken pieces can corrupt a frame. Use a library or converter that sends the whole frame at once.
TCP ADU formatUses a 7-byte MBAP header (transaction id 2, protocol id 2 set to 0, length 2, unit id 1) followed by the PDU. There is no CRC because the TCP layer checks integrity. The standard port is 502.The unit id selects a serial slave behind a gateway, and the transaction id matches a reply to its request.
Maximum sizeThe PDU is at most 253 bytes, so a serial ADU is at most 256 bytes and a TCP ADU at most 260 bytes.A single request can read at most 125 holding registers and write at most 123.
Common functions03 reads holding registers, 06 writes one (the reply echoes the request), 16 (0x10) writes several. An exception reply uses the function code plus 0x80, followed by a code: 01 function not supported, 02 wrong address, 03 wrong value, 04 device failure.Getting an exception is good news. It means the cable and settings are right, and the problem is the address or the value sent.
Address countingIn the data on the wire, addresses start at 0. In the document's example that reads registers 108 to 110, the address sent is 0x006B, which is 107.A number like 40001 in a device manual is holding register number 1, which is address 0 on the wire.
Serial networkOne master and slaves 1 to 247. Number 0 is broadcast (writes only, and there is no reply). The default is 8E1 (even parity), and 9600 and 19200 baud must be supported, with 19200 as the default.If the device is set differently from the program, you see silence or a bad CRC. Set both sides according to the device manual.
Cable and resistorsThe main line is a daisy chain with terminating resistors (150 ohms, or 120 ohms in series with a 1 nF capacitor) at the two ends of the main line only. Bias is applied at one point only, with a pull-up on D1 and a pull-down on D0 of about 450 to 650 ohms. The Common reference line is tied to protective ground at one point. Up to 32 devices can be connected without a repeater.A star layout, several terminating resistors, or no bias at all is the usual cause of intermittent dropouts.
Pin names A/BThe Modbus documents call the two lines D1 and D0. Transceiver makers call them A and B, and each maker may define the polarity the opposite way.If everything is wired right but there is only silence, first try swapping the two wires on one device. It does no harm because the signal is differential.
RS485 transceiver limitsA Texas Instruments application note (slla272d) gives a common-mode range of minus 7 to plus 12 volts, lets the load be counted in unit loads, 32 unit loads per bus for standard transceivers, and says failsafe needs external bias for transceivers without it built in.The maximum number of devices depends on the transceiver model in each unit. Check the device manual.
SecurityOriginal Modbus has no authentication and no encryption. A separate spec, the Modbus Security Protocol, exists, but most devices on the market do not support it yet (the spec list is on the Modbus Organization's specifications page).Anyone who can reach the wire or port 502 can read and write everything. Protect it with network separation.
Summarized from the Modbus Application Protocol V1.1b3, Modbus over Serial Line V1.02, Modbus Messaging on TCP/IP Implementation Guide V1.0b specs and the TI application note slla272d, as read on 2026-11-21. For real work, read the documents for the devices you use.

Overview of the code example

The example is standard Python. There is nothing to pip install and no serial port is needed. It has a simulated Modbus TCP server at 127.0.0.1 holding the registers of a hypothetical power meter, and a client that sends real requests over a socket. For RTU, we build and check the bytes with the same code, because the PDU is identical in both. Only the outer envelope differs.

FilePurpose
frames.pyCRC-16, building and parsing RTU and TCP frames, exceptions, decoding a 32-bit value from two registers in all four orders
sim_server.pyA simulated Modbus TCP server. Supports functions 03, 06 and 16 and answers with exceptions. Unit id 99 never answers, to simulate a dead device.
client.pyA TCP client that checks the reply's transaction id and unit id, and has a timeout
demo.pyRuns all five parts and prints the real bytes
test_modbus.py11 unittest cases
output.txtThe real output of demo.py
README.mdHow to run it, and cautions
Files in the folder examples/modbus-rtu-tcp-rs485-ethernet

Requires Python 3.9 or later. Run python3 demo.py and python3 -m unittest in the example folder. The register map in the example is made-up values that we set ourselves and does not match any device model. Real work must always use the register map from the device manual.

Step 1: the cable layer. Wire RS485 correctly before writing code

Code is not involved yet. This step is about laying the cable. If this layer is wrong, no program can read anything. There are six things to do.

  1. Use twisted-pair cable designed for RS485. Two wires are the signal pair (D1 and D0, or A and B), and the third is the Common reference. If the cable is shielded, connect the shield to ground at one point only.
  2. Run a single main line (daisy chain) from the first device to the next, through to the last one. Short stubs are allowed where necessary. Do not wire a star that fans out from one point into several cables.
  3. Fit terminating resistors (120 or 150 ohms, as the manual specifies) at the two ends of the main line only, not at devices in the middle. Many models have a switch or jumper to turn on a built-in resistor.
  4. Apply bias at one point on the bus (usually at the master or gateway) so the line sits at a stable level when nobody is transmitting. Without it, a receiver may interpret noise as data.
  5. Check that there is only one master. If two programs open the same port, or two masters sit on one bus, their requests will collide.
  6. If the main line is long or noisy, lower the baud rate before replacing the cable, because lower speeds tolerate reflections better.

The most confusing thing is the pin names. The Modbus documents say D1 and D0. Transceiver makers say A and B, and some define the polarity the opposite way. If all the settings are right and it is still silent, swap the two wires on one device. This is safe because the signal is differential, and nothing burns out from reversed polarity.

Caution: the resistor and bias requirements above are summarized from the serial line spec V1.02 and the TI note. They were checked against documents only and not tested on a real cable. A real installation must follow the device manufacturer's manual and be measured with suitable instruments.

Step 2: set the serial parameters and slave number to match on both sides

The device side and the program side must match on every setting: baud rate (9600 or 19200 are the speeds the spec requires devices to support, other speeds depend on the device), number of data bits (8 for RTU), parity, and stop bits. The default in the spec is 8E1, but many devices use 8N1 or 8N2. Set it according to the device manual. Do not guess.

Slave numbers must be unique on the bus. The usable range is 1 to 247. Number 0 is broadcast with no reply. If they do not match, what you see is complete silence or a bad CRC, not an exception, because a corrupted frame is dropped silently under the protocol's rules.

With Modbus TCP, there is no baud rate or parity any more, but there are other things to set: the IP address, the port (502) and the unit id. A pure Ethernet device often ignores the unit id, but a gateway uses it to choose which serial slave to forward to.

Step 3: count registers correctly, from 0 or from 1

Device manuals often write registers as 40001, 40002 and so on, or 30001 (the leading digit is an old convention for the type: 4 is a holding register, 3 is an input register). The rest is the register's sequence number, which counts from 1, but the data on the wire starts at address 0. In short, 40001 is holding register number 1, and on the wire you send address 0.

Some libraries take wire-style addresses (starting at 0), some take manual-style (starting at 1), and some strip the leading digit for you. So read the library's documentation and test with a register whose value you already know, such as the model number, or a voltage measured against another meter. Even the example in the spec is confusing. Read the example that says registers 108 to 110, then sends 0x006B, which is 107, because 108 is counted from 1.

frames.py · lines 38–49
# ---- PDU (same for RTU and TCP) ----
def pdu_read_holding(addr, qty):
    return struct.pack(">BHH", 0x03, addr, qty)


def pdu_write_single(addr, value):
    return struct.pack(">BHH", 0x06, addr, value)


def pdu_write_multiple(addr, values):
    n = len(values)
    return struct.pack(f">BHHB{n}H", 0x10, addr, n, 2 * n, *values)
frames.py: PDUs for functions 03, 06 and 16. The address you pass in is the wire number, starting at 0

Step 4: build the RTU frame and CRC

An RTU frame is the slave number, then the PDU, then a two-byte CRC appended with the low byte sent first. The CRC Modbus uses is CRC-16 starting at 0xFFFF, with the reflected polynomial 0xA001 and no final xor. You can test it with the standard value: the CRC of the message 123456789 must be 0x4B37.

frames.py · lines 15–35
def crc16(data: bytes) -> int:
    """CRC-16/MODBUS: init 0xFFFF, polynomial 0xA001 (reflected), no final xor."""
    crc = 0xFFFF
    for b in data:
        crc ^= b
        for _ in range(8):
            crc = (crc >> 1) ^ 0xA001 if crc & 1 else crc >> 1
    return crc


def with_crc(body: bytes) -> bytes:
    return body + struct.pack("<H", crc16(body))  # low byte first


def check_crc(frame: bytes) -> bytes:
    """Return the frame without CRC, or raise ValueError when CRC is wrong."""
    if len(frame) < 4:
        raise ValueError("frame too short")
    if crc16(frame[:-2]) != struct.unpack("<H", frame[-2:])[0]:
        raise ValueError("bad CRC")
    return frame[:-2]
frames.py: crc16, building a frame (with_crc) and checking a frame (check_crc)

The receiver always checks the CRC first. If it does not match, drop the whole frame, do not reply, and do not try to repair the value. A master that gets no reply waits until the timeout and then tries again.

Step 5: build the TCP frame and read the reply

Modbus TCP uses the same PDU but changes the envelope to an MBAP header. It carries a transaction id that the requester sets and the responder must echo back, which allows several requests to be in flight at once while the replies are still matched correctly. There is no CRC because TCP already checks.

frames.py · lines 72–81
# ---- TCP: MBAP = transaction(2) protocol(2)=0 length(2) unit(1) ----
def tcp_adu(tid, unit, pdu):
    return struct.pack(">HHHB", tid, 0, len(pdu) + 1, unit) + pdu


def mbap_parse(header: bytes):
    tid, proto, length, unit = struct.unpack(">HHHB", header)
    if proto != 0:
        raise ValueError("protocol id must be 0")
    return tid, length, unit
frames.py: tcp_adu builds the MBAP header and mbap_parse parses it

On the client side, the call function sends the request, reads the 7-byte header first, checks the transaction id and unit id, and then reads the PDU for the length the header gives. The checks are there so that if an old reply is still sitting on the connection, we do not use the reply to an earlier request.

client.py · lines 23–29
    def call(self, pdu):
        self.tid = (self.tid + 1) & 0xFFFF
        self.sock.sendall(tcp_adu(self.tid, self.unit, pdu))
        tid, length, unit = mbap_parse(self._recv(7))
        if tid != self.tid or unit != self.unit:
            raise ValueError(f"reply for tid={tid} unit={unit}, expected {self.tid}/{self.unit}")
        return self._recv(length - 1)
client.py: call checks the transaction id and unit id before returning the PDU

Step 6: the simulated device side and exception replies

The simulated server holds registers at addresses 0 to 7. Registers 6 and 7 are writable and the rest are read-only. The decision about which exception code to return lives in the handle_pdu function, with a simple rule: an unknown function gets 01, an address range outside the map gets 02, and a quantity or value outside the allowed range gets 03.

sim_server.py · lines 20–44
def handle_pdu(pdu: bytes) -> bytes:
    fn = pdu[0]
    if fn == 0x03:
        addr, qty = struct.unpack(">HH", pdu[1:5])
        if not 1 <= qty <= 125:
            return exception(fn, 3)
        if any(a not in REGS for a in range(addr, addr + qty)):
            return exception(fn, 2)
        return struct.pack(f">BB{qty}H", fn, 2 * qty, *[REGS[a] for a in range(addr, addr + qty)])
    if fn == 0x06:
        addr, val = struct.unpack(">HH", pdu[1:5])
        if addr not in WRITABLE:
            return exception(fn, 2)
        REGS[addr] = val
        return pdu  # response echoes the request
    if fn == 0x10:
        addr, qty, nbytes = struct.unpack(">HHB", pdu[1:6])
        if not 1 <= qty <= 123 or nbytes != 2 * qty:
            return exception(fn, 3)
        if any(a not in WRITABLE for a in range(addr, addr + qty)):
            return exception(fn, 2)
        for i, v in enumerate(struct.unpack(f">{qty}H", pdu[6:6 + nbytes])):
            REGS[addr + i] = v
        return struct.pack(">BHH", fn, addr, qty)
    return exception(fn, 1)
sim_server.py: handle_pdu supports functions 03, 06 and 16 and returns exceptions 01, 02 and 03

Real output from a run

Run python3 demo.py in the example folder. The result below is the real stdout saved in output.txt.

output.txt
== 1. TCP: read 6 holding registers from address 0 ==
request  : 00 01 00 00 00 06 01 03 00 00 00 06
registers: ['0x0901', '0x04D2', '0x449A', '0x5000', '0x5000', '0x449A']
voltage  : 230.5 V   current: 12.34 A
kWh ABCD : 1234.5
kWh CDAB : 1234.5
wrong order (read ABCD data as CDAB): 8607918080.0
== 2. TCP: write 06 and 16, read back ==
write single addr 6 = 500 -> True
write multiple addr 6..7 = [10, 20] -> 10 00 06 00 02
read back addr 6..7: [10, 20]
== 3. exception responses ==
read address 100 (no such register): fn 0x03 -> exception 2 ILLEGAL DATA ADDRESS
read 4..8 (crosses the end of the map): fn 0x03 -> exception 2 ILLEGAL DATA ADDRESS
write read-only address 0: fn 0x06 -> exception 2 ILLEGAL DATA ADDRESS
read quantity 0: fn 0x03 -> exception 3 ILLEGAL DATA VALUE
unknown function 0x41 -> pdu c1 01 (0xC1 = 0x41 + 0x80, code 01)
== 4. timeout: unit 99 never answers ==
TimeoutError after 0.5 s -> treat as 'device offline', do not guess a value
== 5. RTU frames (no serial port: bytes only) ==
request  : 01 03 00 00 00 06 c5 c8  (last 2 bytes = CRC, low byte first)
crc16    : 0xC8C5
response : 01 03 0c 09 01 04 d2 44 9a 50 00 50 00 44 9a df 11
parsed   : slave 1 registers ['0x0901', '0x04D2', '0x449A', '0x5000', '0x5000', '0x449A']
flip 1 bit in byte 5 -> bad CRC
RTU exception frame 01 83 02 c0 f1 -> fn 0x03 -> exception 2 ILLEGAL DATA ADDRESS
output.txt: real output of python3 demo.py
  1. Part 1: the request 00 01 00 00 00 06 01 03 00 00 00 06 reads 6 registers starting at address 0 and gives a voltage of 230.5 volts (raw 2305 times 0.1) and a current of 12.34 amps (raw 1234 times 0.01).
  2. The kWh value 1234.5 reads correctly in both orders, because we placed the same data in ABCD and CDAB order and chose the matching decode order. If you decode ABCD data as CDAB, you get 8607918080.0, which is the symptom in the third situation.
  3. Part 2: write with function 06, then write two registers with function 16 (the reply is the address and the number written), then read back and get the values that were written.
  4. Part 3: the four kinds of exception. Reading address 100, which does not exist, and reading past the last register both give code 02. Writing a register that is not writable gives 02. Reading a quantity of 0 gives 03. The unknown function 0x41 gives c1 01, which is 0x41 plus 0x80 with code 01.
  5. Part 4: unit id 99 never answers. The client gets a TimeoutError, which must be read as the device being offline, not as a reason to substitute the old value or zero.
  6. Part 5: the RTU frame. The request is 01 03 00 00 00 06 c5 c8 (the CRC is 0xC8C5, sent low byte first as c5 c8). The 17-byte reply decodes back to the same registers. Flipping one bit in the frame makes the CRC fail, and the exception frame 01 83 02 c0 f1 decodes as a wrong address.

Byte by byte: a request to read 6 registers, in both TCP and RTU

It is the same request, reading 6 holding registers starting at address 0 from device number 1, wrapped in two kinds of envelope.

PositionTCP (12 bytes)RTU (8 bytes)Meaning
1 to 200 01-transaction id (TCP only)
3 to 400 00-protocol id, always 0 (TCP only)
5 to 600 06-length: the number of bytes after this field, including the unit id, which is 1 plus 5, equal to 6
TCP 7 / RTU 10101unit id (TCP) or slave number (RTU)
TCP 8 / RTU 20303function: read holding registers
TCP 9 to 10 / RTU 3 to 400 0000 00start address 0
TCP 11 to 12 / RTU 5 to 600 0600 06register count 6
RTU 7 to 8-c5 c8CRC-16, low byte first (actual value 0xC8C5)
Real bytes from output.txt part 1 (TCP) and part 5 (RTU). All numbers are big-endian except the CRC.

The part that repeats is the 5-byte PDU (03 00 00 00 06), which is the actual command. The part that differs is the envelope. This is why a gateway can convert RTU to TCP without understanding the content: it removes one envelope and wraps the other kind.

About 32-bit values too: the value 1234.5 as a 32-bit float is 0x449A5000, split into two registers, 0x449A and 0x5000. If the manufacturer sends the upper one first (ABCD), reading it directly is correct. If it sends the lower one first (CDAB), swap the two registers before decoding. There are two more orders that also swap the bytes within each register (BADC, DCBA). Some manuals do not say clearly. A method that works is to write down a value you know, such as a voltage measured on another instrument, then try decoding all four ways. Only one gives a sensible value.

frames.py · lines 84–91
# ---- 32-bit values over two registers ----
def regs_to_float(r0, r1, order="ABCD"):
    """ABCD = first register holds the high word (big-endian)
    CDAB = words swapped. BADC / DCBA also swap the bytes inside words."""
    a, b = struct.pack(">HH", r0, r1)[:2], struct.pack(">HH", r0, r1)[2:]
    raw = {"ABCD": a + b, "CDAB": b + a,
           "BADC": a[::-1] + b[::-1], "DCBA": b[::-1] + a[::-1]}[order]
    return struct.unpack(">f", raw)[0]
frames.py: regs_to_float decodes a 32-bit float from two registers in the chosen order

What the RTU part of the example does

demo.py · lines 46–66
print("== 5. RTU frames (no serial port: bytes only) ==")
frame = rtu_request(1, pdu_read_holding(0, 6))
print("request  :", frame.hex(" "), " (last 2 bytes = CRC, low byte first)")
print(f"crc16    : 0x{crc16(frame[:-2]):04X}")
resp_body = bytes([1]) + struct.pack(">BB6H", 0x03, 12, *regs)
resp = with_crc(resp_body)
print("response :", resp.hex(" "))
slave, pdu = rtu_parse(resp)
print("parsed   : slave", slave, "registers", [f"0x{r:04X}" for r in parse_read_response(pdu)])
bad = bytearray(resp)
bad[5] ^= 0x01
try:
    rtu_parse(bytes(bad))
except ValueError as e:
    print("flip 1 bit in byte 5 ->", e)
exc = with_crc(bytes([1, 0x83, 0x02]))
slave, pdu = rtu_parse(exc)
try:
    parse_read_response(pdu)
except ModbusException as e:
    print("RTU exception frame", exc.hex(" "), "->", e)
demo.py part 5: builds the RTU request and reply, checks the CRC, flips a bit to break the CRC, and parses an exception

This part does not touch a real serial port, so it proves only that the frame and CRC are correct. It does not prove anything about timing, such as the 3.5-character silence or the direction switching of an RS485 transceiver. Those two things must be tested on real hardware or handled by a library.

How the test suite works

test_modbus.py has 11 cases and checks four groups. The CRC group checks against the standard value 0x4B37 for the message 123456789 and compares with a second, table-based way of computing it to confirm both give the same result. The frame group checks the example PDU from the spec (reading from address 107, quantity 3, gives 03 00 6b 00 03), a round trip of RTU, and an MBAP that matches the example in the TCP implementation guide. The 32-bit group checks that all four orders decode back to the value that was encoded. The server group checks reading, writing then reading back, a wrong address, and a timeout.

A plain observation: the example CRC for the request 01 03 00 00 00 0A is c5 cd. This is a widely published example and was not taken directly from the spec. The spec gives only the algorithm, so we check with two separately written computation methods plus the standard check value.

README.md
# ตัวอย่าง: Modbus TCP และ RTU ระดับ byte (อ่าน holding register, CRC, เสียบเกินขอบเขต, timeout)

ตัวอย่างประกอบบทความ "modbus-rtu-tcp-rs485-ethernet" ของ BT San Technology

สิ่งที่แสดง

- `frames.py` ประกอบและแกะ frame: CRC-16/MODBUS, RTU (slave + PDU + CRC), TCP (MBAP header 7 byte + PDU), exception response และการถอดค่า 32 บิตจากสอง register ในลำดับ word ทั้งสี่แบบ
- `sim_server.py` เซิร์ฟเวอร์ Modbus TCP จำลองที่ 127.0.0.1 ถือ register ของมิเตอร์ไฟฟ้า (แรงดัน กระแส kWh แบบ float32) รองรับ function 03, 06, 16 ตอบ exception 01/02/03 และมี unit id 99 ที่ไม่ตอบเลย (จำลองอุปกรณ์ตายหลัง gateway)
- `client.py` ไคลเอนต์ TCP ขนาดเล็ก ตรวจ transaction id และ unit id ของคำตอบ มี timeout
- `demo.py` สาธิตทั้งหมดและพิมพ์ byte จริงของ frame
- `test_modbus.py` ชุดทดสอบ `unittest` 11 กรณี
- `output.txt` ผลลัพธ์จริงของ `python3 demo.py` ที่รันเมื่อ 2026-11-21

ต้องมี: Python 3.9 ขึ้นไป (ทดสอบกับ 3.14) ใช้เฉพาะ standard library ไม่ต้อง pip install ไม่มีพอร์ตอนุกรมจริง ส่วน RTU เป็นการสร้างและตรวจ byte เท่านั้น เครือข่ายใช้เฉพาะ 127.0.0.1 พอร์ตสุ่ม

```
python3 demo.py
python3 -m unittest -v
```

หมายเหตุ: นี่เป็นตัวอย่างเพื่อการเรียนรู้ ไม่ใช่โค้ด production แผนที่ register เป็นค่าสมมติที่เราตั้งขึ้นเอง ไม่ตรงกับอุปกรณ์รุ่นใด ต้องใช้ register map จากคู่มือของอุปกรณ์จริงเสมอ งานจริงควรใช้ไลบรารีที่มีผู้ดูแล เช่น pymodbus หรือ libmodbus (ตัวอย่างนี้ไม่มี retry, ไม่มี reconnect, ไม่มีการจัดการ frame ที่ขาดกลางทางแบบครบ)
README.md in the example folder (how to run, requirements and cautions)

Going to production: use a library and budget the polling time

This example is meant to show the bytes, not to be used as is. Real work uses a maintained library such as pymodbus (Python, supporting RTU, TCP, TLS, UDP and RTU over TCP, both sync and async, including a simulator) or libmodbus (C). These libraries handle inter-frame timing, reconnection and edge cases that we did not write.

  • Bounded retries: on a timeout or bad CRC, retry 1 to 3 times, then mark the device offline. Do not retry forever, because one dead device slows down the polling cycle of the whole bus.
  • Polling time budget: a serial bus handles one request at a time. The time per request is the transmission time of the request and reply bytes, plus the device's processing time and the gaps between frames. At 9600 baud, one character (11 bits) takes about 1.15 milliseconds. An 8-byte request plus a 17-byte reply, 25 bytes in total, takes about 29 milliseconds on the wire, not counting the device's processing time. Multiply by the number of devices to find the lowest possible polling cycle, then add margin.
  • Read in blocks: reading 20 adjacent registers in one request is much faster than 20 requests of one register each, but it must not exceed 125 registers and must not cross an address range the device does not have (per the result of part 3 above, the whole request gets an exception).
  • Do not write too often: some writable registers are in EEPROM, which has a limited number of write cycles. Check the manual before setting a program to write in every cycle.
  • Time: always store the time of the reading together with the value, and keep the status, online or offline, separate from the value, so charts do not draw a straight line through a period when nothing could be read.
  • Security: Modbus has no authentication. Anyone who can connect to the cable or reach port 502 can write values. Never expose port 502 to the internet. Separate the control device network from the office network, add a firewall that allows only the machines that need to read, and give the program read-only rights if it does not need to write.

If you need a gateway to convert RTU to TCP

A gateway lets you read RS485 devices from the LAN. A machine on the IT side sends a Modbus TCP request to the gateway, and the gateway uses the unit id to choose the slave and converts it to RTU on the wire. Note that a gateway can send only one request at a time onto the serial bus. Several programs firing at once are queued, so the overall speed is always limited by the serial bus, and one dead device makes every request through the gateway wait for the timeout.

Applying it to business work

  • A factory that logs power per machine (hypothetical): 12 meters on two RS485 lines, 6 per line, connected to a gateway. The system stores readings in a database every 5 seconds and calculates the energy cost per unit produced. The decision to make is to split the buses so the polling cycle is short enough.
  • Collecting data from an old machine (hypothetical): an older machine has only an RS485 port and a one-page manual in English. Reading it with Modbus is the way that does not touch the existing control program. The time goes into interpreting the register map and checking values against the machine's display.
  • A cold room alert (hypothetical): several temperature controllers send values through a gateway to a dashboard. It must clearly distinguish offline from high temperature, because if a reading fails and the old value stays on screen, the operator will wrongly think everything is normal.

Common mistakes

  • Wiring a star or putting terminating resistors at several points, so the bus drops out intermittently even though everything read fine on day one.
  • No bias, then noise being read as data when the bus is idle.
  • Never trying to swap the two wires, and replacing a device that was not faulty.
  • Mismatched baud rate or parity, getting only silence and then suspecting the program layer.
  • Counting registers off by one (0 versus 1) and unknowingly reading a neighboring register.
  • Decoding a 32-bit value in the wrong order and getting a number millions of times too large.
  • Forgetting to apply the scale (for example, raw 2305 means 230.5 volts), or forgetting that some values are signed integers.
  • Showing the old value or zero after a timeout instead of showing offline.
  • Exposing port 502 to the internet, or putting it on the same network as guest Wi-Fi.

Checklist before going live

  1. Keep the manual and register map for every device model. Record the data type, scale, unit and word order.
  2. Check that the cable is a daisy chain with terminating resistors at two places, bias at one, and the shield grounded at one point.
  3. Set baud rate, parity and stop bits to match on both sides, and make sure the slave ids are unique.
  4. Test by reading a register with a known value (such as the model number) to confirm whether counting starts from 0 or 1.
  5. Test all four 32-bit orders against a value you know from the machine's display.
  6. Calculate the polling time budget for the whole bus and decide the number of retries.
  7. Show the offline status separately from the readings. Test it by actually unplugging one device.
  8. Block port 502 with a firewall and separate the control device network from the office network.
  9. Write down the test results, the program version and how the devices are configured, for whoever takes over.

Cautions about the example: there is no real serial port, no inter-frame timing, no retry or reconnect, and not every case of a frame arriving in pieces is handled. The register map is made-up values, and it was not tested with a real meter or gateway. Use it as a learning exercise, not as code ready for real use.

References

  1. Modbus Organization — Specifications (accessed 2026-11-21)
  2. Modbus Application Protocol Specification V1.1b3 (accessed 2026-11-21)
  3. Modbus over Serial Line Specification and Implementation Guide V1.02 (accessed 2026-11-21)
  4. Modbus Messaging on TCP/IP Implementation Guide V1.0b (accessed 2026-11-21)
  5. Texas Instruments — slla272d RS-485 application note (accessed 2026-11-21)
  6. pymodbus documentation (accessed 2026-11-21)

Add us on LINE

Scan with the LINE app on your phone

QR code to add LINE @Bankoos

LINE ID: @Bankoos

Open LINE on this computer