Protocols and integration

Modbus RTU over RS-485 on a Raspberry Pi 5 or CM5

Updated

To talk Modbus RTU from a Raspberry Pi 5 or CM5, enable UART0 on GPIO 14/15 with dtoverlay=uart0-pi5, connect a 3.3 V RS-485 transceiver, terminate both ends of the bus with 150 ohm, and bias it in one place. Then read a register with mbpoll or a ten-line pymodbus script. Most failures come from five things: swapped A/B, wrong parity, wrong address offset, missing termination or bias, or the serial console still holding the port.

Assumed here: Raspberry Pi 5 or CM5 on Raspberry Pi OS Bookworm or Trixie (64-bit), pymodbus 3.16.2, and a half-duplex (two-wire) Modbus RTU bus.

Which UART to use on a Pi 5 or CM5

The Pi 5 changed the serial layout. Per the Raspberry Pi documentation, the primary UART on a Pi 5 is UART10, on the dedicated debug header, and /dev/serial0 points to /dev/ttyAMA10. The 40-pin header UARTs are off until you load an overlay. The CM5 datasheet lists up to five UARTs on its GPIO bank.

Overlay TX/RX GPIOs RTS/CTS GPIOs Device
uart0-pi5 14 / 15 17 / 16 /dev/ttyAMA0
uart1-pi5 0 / 1 3 / 2 /dev/ttyAMA1
uart2-pi5 4 / 5 7 / 6 /dev/ttyAMA2
uart3-pi5 8 / 9 11 / 10 /dev/ttyAMA3
uart4-pi5 12 / 13 15 / 14 /dev/ttyAMA4

Pin assignments come from the overlays README. Check device names on your system with ls -l /dev/ttyAMA* after rebooting, since they follow the order the kernel registers the UARTs.

Add to /boot/firmware/config.txt:

# UART0 on GPIO 14/15; the kernel drives the transceiver's DE/RE pin from RTS (GPIO 17)
dtoverlay=uart0-pi5,rs485

Leave off ,rs485 if your transceiver switches direction by itself. Then free the port from the login console: sudo raspi-config, Interface Options, Serial Port, answer No to the login shell and Yes to the serial hardware, and reboot. Add your user to the dialout group (sudo usermod -aG dialout $USER, then log in again) so programs can open the port without root.

Choosing a transceiver

The Pi’s GPIO is 3.3 V and, in the Raspberry Pi hardware documentation’s words, not 5 V tolerant. The transceiver’s receive output connects straight to a GPIO, so it must be a 3.3 V part, or a 5 V part with a separate 3.3 V logic supply.

Option Direction control Use it when
3.3 V transceiver, for example TI THVD1450 (3.3 V to 5 V, ±18 kV IEC ESD) DE/RE from GPIO 17 via rs485 overlay Short runs inside one panel, shared ground
Isolated transceiver, for example TI ISO1410 DE/RE from GPIO 17 Devices on other power supplies, long runs, motors and VFDs nearby
“Auto-direction” module Switches on transmitted data Breadboard tests; check it works at your baud rate
USB RS-485 adapter (FTDI-based) Handled in the adapter You want no GPIO wiring; port is /dev/ttyUSB0
HAT with SPI UART (SC16IS752 and similar) Handled by the driver Two or more RS-485 ports; follow the HAT’s overlay

Many cheap modules use a 5 V-only MAX485-class chip; powered at 5 V, they put 5 V on the Pi’s RX pin. Check the chip marking before connecting one.

With the rs485 overlay parameter, the kernel’s RS485 mode raises RTS while transmitting and drops it after the last bit. Tie the transceiver’s DE and /RE pins together and connect them to GPIO 17. Your program does not have to toggle anything.

Termination, biasing and grounding

These rules come from the Modbus over Serial Line specification V1.02, section 3.4:

  • Topology. One trunk cable, daisy-chained. Drops (stubs) from the trunk no longer than 20 m. No star wiring.
  • Termination. One terminator at each end of the trunk, between D0 and D1, and no more than two in total. The spec gives 150 ohm, 0.5 W, or 120 ohm in series with 1 nF where the line is biased. Many devices have a built-in terminator switch; turn it on only at the two end devices.
  • Biasing (polarization). If any device needs it, fit one pull-up from D1 to 5 V and one pull-down from D0 to common, each 450 to 650 ohm, at one point on the bus, usually the master. Many master adapters have bias resistors built in; check before adding more.
  • Common. A third conductor connects the signal common of every device, grounded to protective earth at one point. Two-wire RS-485 still needs this wire.
  • Length. Up to 1,000 m at 9,600 baud or below with AWG 26 or thicker cable. Up to 32 devices without a repeater.

For a short bench test (one device, two metres of cable at 9,600 or 19,200 baud), termination rarely matters. On a real bus it does. TI’s RS-485 Design Guide explains why in more depth.

The spec names the lines D0 (A) and D1 (B), with D1 positive in the idle state. Transceiver vendors often label the same pin the other way round. If nothing answers, swap the two data wires; it does no harm.

Serial settings

Modbus RTU defaults to 19,200 baud, 8 data bits, even parity, 1 stop bit (8E1). The specification also allows no parity, but then requires 2 stop bits (8N2). Many devices ship as 9600 8N1 anyway. Every device on the bus must use the same setting, and each needs a unique device ID from 1 to 247.

Read a register

The quickest test is mbpoll (sudo apt install mbpoll). This reads two holding registers starting at address 0 from device 1, once:

mbpoll -m rtu -a 1 -b 19200 -P even -t 4 -r 1 -c 2 -1 /dev/ttyAMA0

mbpoll numbers registers from 1 by default (manual); add -0 to use the zero-based address that goes on the wire. Use -t 3 for input registers.

The same read in Python, using pymodbus 3.16.2:

python3 -m venv ~/modbus && ~/modbus/bin/pip install pymodbus==3.16.2 pyserial==3.5

Save as read_register.py:

"""Read holding or input registers from one Modbus RTU device and print them."""

import argparse
import sys

from pymodbus import ModbusException
from pymodbus.client import ModbusSerialClient

parser = argparse.ArgumentParser()
parser.add_argument("--port", default="/dev/ttyAMA0")
parser.add_argument("--baud", type=int, default=19200)
parser.add_argument("--parity", choices=["N", "E", "O"], default="E")
parser.add_argument("--stopbits", type=int, choices=[1, 2], default=1)
parser.add_argument("--device-id", type=int, default=1)
parser.add_argument("--address", type=int, default=0, help="zero-based register address, as sent on the wire")
parser.add_argument("--count", type=int, default=1)
parser.add_argument("--input", action="store_true", help="read input registers (function 4) instead of holding (3)")
args = parser.parse_args()

client = ModbusSerialClient(
    args.port, baudrate=args.baud, parity=args.parity, stopbits=args.stopbits, bytesize=8, timeout=1, retries=1
)
if not client.connect():
    sys.exit(f"cannot open {args.port}")
read = client.read_input_registers if args.input else client.read_holding_registers
try:
    response = read(args.address, count=args.count, device_id=args.device_id)
except ModbusException as exc:
    sys.exit(f"no valid response: {exc}")
finally:
    client.close()
if response.isError():
    sys.exit(f"device answered with Modbus exception code {response.exception_code}")
for offset, value in enumerate(response.registers):
    print(f"register {args.address + offset}: {value} (0x{value:04X})")
~/modbus/bin/python read_register.py --port /dev/ttyAMA0 --device-id 1 --address 0 --count 2

Output looks like register 0: 215 (0x00D7). Scale it using the device manual: 215 with a factor of 0.1 is 21.5.

Addresses: 40001 is not 40001

Manuals write registers three ways: “40001”, “holding register 1” or “address 0x0000”. All three usually mean the same register, sent on the wire as address 0 with function code 3. The leading 4 means holding register (function 3), 3 means input register (function 4). pymodbus takes the wire address, so subtract 40001 or 30001. If you get exception code 2 (illegal data address) or values that are plausible but belong to the neighbouring register, you are off by one.

Troubleshooting

Symptom Likely cause Check or fix
cannot open /dev/ttyAMA0 or permission denied Overlay not loaded, or user not in dialout ls -l /dev/ttyAMA*; groups; reboot after editing config.txt
Garbage or login prompt on the bus Serial console still enabled raspi-config: login shell No; remove console=serial0,... from /boot/firmware/cmdline.txt
Timeout, no reply at all A/B swapped, wrong device ID, wrong baud or parity Swap A/B; confirm ID and 8E1 vs 8N1 on the device display or DIP switches
Timeout, TX LED blinks, RX never Transceiver stays in transmit, or never transmits DE/RE wired to GPIO 17 and overlay has ,rs485; or ,rs485_invert_rts for active-low
Echo of your own request, then error Full-duplex receive on a half-duplex bus Remove rs485_full_duplex; keep /RE tied to DE
CRC errors, intermittent replies Missing termination or bias, stubs too long, no common wire Terminate both ends only; bias once; run the common conductor
Works at 9600, fails at 115200 Cable length or auto-direction module too slow Lower the baud rate; use DE/RE control
Exception code 2 Address does not exist on the device Check the 40001 offset; read count past the end of a block
Exception code 1 Wrong function code for that register type Holding (3) vs input (4)
Exception code 6 Device busy Increase poll interval; retry
One device answers, a second does not Duplicate device ID or different serial settings Connect devices one at a time and set unique IDs
Errors when a motor or VFD starts Ground potential difference or noise Isolated transceiver, shielded twisted pair, shield grounded at one end

Next step

To publish these readings to MQTT or Modbus TCP, see Raspberry Pi Modbus RTU to TCP/MQTT gateway.

Sources

  1. Raspberry Pi documentation, Configuration (UARTs and serial console), accessed 2026-11-19
  2. Raspberry Pi documentation, Raspberry Pi hardware (GPIO voltage), accessed 2026-11-19
  3. Raspberry Pi device tree overlays README (uart0-pi5 to uart4-pi5), accessed 2026-11-19
  4. Raspberry Pi Compute Module 5 datasheet, accessed 2026-11-19
  5. Modbus Organization, specifications (Modbus over Serial Line Specification and Implementation Guide V1.02, 2006), accessed 2026-11-19
  6. Texas Instruments, The RS-485 Design Guide (SLLA272), accessed 2026-11-19
  7. Texas Instruments THVD1450 product page, accessed 2026-11-19
  8. Texas Instruments ISO1410 product page, accessed 2026-11-19
  9. Linux kernel documentation, RS485 serial communications, accessed 2026-11-19
  10. mbpoll manual page (Debian trixie), accessed 2026-11-19
  11. pymodbus on PyPI (version 3.16.2), accessed 2026-11-19