Blog · Embedded software

Modbus RTU (RS-485) with STM32: What to Watch for in Hardware and Firmware

Modbus RTU is still one of the most widely used fieldbus protocols in industry. It looks simple on paper, but a device that works reliably in the field depends on getting a few critical details right in both hardware and firmware.

Modbus RTU is a simple serial communication protocol widely used to exchange data between PLCs, drives, energy analyzers and sensors. The physical layer is usually RS-485. A bus has one client (formerly called the master) and server devices (formerly called slaves) with addresses from 1 to 247; the client queries and the server responds.

Because the protocol is simple, it is easy to assume it will "just work"; yet most problems in the field come from hardware details and timing. Below, we have grouped what to watch for when designing an STM32-based device under two headings: hardware and firmware.

Hardware: The RS-485 Side

Transceiver Selection

  • Since the STM32 runs from 3.3 V, an RS-485 transceiver powered from 3.3 V removes the need for level shifting.
  • Transceivers with a fail-safe receiver keep it from outputting random characters when the bus is idle or disconnected.
  • The unit load rating determines how many devices can be connected to the bus. The standard specifies 32 unit loads per bus; with 1/8 unit-load transceivers, many more devices can share the same bus.
  • On long cable runs, slew-rate-limited transceivers reduce reflections and radiated noise.

Termination and Biasing

  • Termination: A resistor close to the cable's characteristic impedance (typically 120 Ω) goes only at the two physical ends of the bus. Fitting a termination resistor on every device overloads the bus. Making termination selectable on the board with a jumper or a switch is a big help in the field.
  • Biasing: When the bus is idle, there must be a defined voltage difference between A and B. To achieve this, A is pulled up to the supply and B is pulled down to ground through resistors at one point on the bus. Fail-safe transceivers reduce this need, but do not always eliminate it completely.

Protection and Isolation

Field cables are long and exposed to external disturbances. The bus is protected with TVS diodes (asymmetric types that suit the RS-485 common-mode range of −7 V to +12 V) and, where needed, series resistors or PTC fuses. In industrial environments where there may be a ground potential difference between devices, isolating the bus with a digital isolator and an isolated DC-DC converter is the safest solution.

Cabling

  • Use twisted-pair cable; with shielded cable, ground the shield at a single point.
  • Connect devices in a daisy chain; avoid star topologies and long stubs.
  • Run a common reference (GND) conductor alongside A and B.

Firmware: The STM32 Side

Direction Control (DE/RE)

RS-485 is half-duplex: only one device talks at a time. The driver is enabled (DE) before transmitting and released once transmission is complete. The most common mistake is releasing the driver while the last byte is still being sent; the end of that byte is then corrupted and the other side sees a CRC error.

  • Release the driver when the USART's transmission complete (TC) flag is set. The transmit buffer empty (TXE) flag is set while the last byte is still on the bus.
  • The USART peripherals of many newer series, such as the STM32F0, F3, G0, G4, L4 and H7, have a hardware driver enable (DE) output. This makes direction control independent of software timing; check the reference manual for the series you are using.

Character Format

The default character format in the Modbus specification is 8 data bits, even parity and 1 stop bit (8E1). If no parity is used, 2 stop bits are specified (8N2). Devices using 8N1 are also common in the field; what matters is that all devices on the bus use the same setting. Making this setting adjustable from the device menu or the configuration software is very useful in the field.

Frame Timing

In Modbus RTU, frames must be separated by at least 3.5 character times of silence (the inter-frame gap, t3.5), and the gap between characters within a frame must not exceed 1.5 character times (t1.5). For an 11-bit character (start bit, 8 data bits, parity bit and stop bit), one character time is 11 / baud rate:

Baud rate1 character3.5 characters
9600≈ 1.15 ms≈ 4.0 ms
19200≈ 0.57 ms≈ 2.0 ms
38400 and above≈ 0.29 ms or less1.75 ms (recommended fixed value)

For baud rates above 19200, the specification recommends fixed values of 750 µs for 1.5 characters and 1.75 ms for 3.5 characters.

Detecting the End of a Frame

An efficient approach on the STM32 is to receive into a buffer with DMA and detect the end of the frame separately:

  • The idle line (IDLE) interrupt is a common and practical method; however, it fires after a gap of about one character time and does not guarantee 3.5 characters.
  • For full compliance with the specification, the 3.5-character silence is measured with a timer (TIM) that is restarted on every received byte.
  • The receiver timeout feature of the USART peripherals in some STM32 series lets the hardware count this interval in bit times.

CRC Calculation

Every frame ends with a 16-bit CRC. The Modbus CRC is calculated with an initial value of 0xFFFF and the polynomial 0xA001 (0x8005 bit-reversed); the low byte goes first in the frame. A simple C implementation:

uint16_t modbus_crc16(const uint8_t *buf, uint16_t len)
{
    uint16_t crc = 0xFFFF;
    for (uint16_t i = 0; i < len; i++) {
        crc ^= buf[i];
        for (uint8_t b = 0; b < 8; b++)
            crc = (crc & 1u) ? (uint16_t)((crc >> 1) ^ 0xA001u) : (uint16_t)(crc >> 1);
    }
    return crc; /* the low byte goes into the frame first, then the high byte */
}

At high baud rates or under heavy load, a table-driven implementation is faster. The hardware CRC unit in some STM32 series can also be used once its polynomial and bit order are configured.

Function Codes and the Register Map

The most commonly used function codes:

CodeFunction
03Read Holding Registers
04Read Input Registers
06Write Single Register
16 (0x10)Write Multiple Registers

When an unsupported request arrives, the device should return an exception code with the most significant bit of the function code set (code + 0x80): 01 Illegal Function, 02 Illegal Data Address, 03 Illegal Data Value. Documenting two points in the register map prevents most of the confusion in the field: whether addresses start at 0 or 1 (e.g., the 40001 notation) and in which order 32-bit values are written to the two registers.

Common Problems in the Field

  • A and B swapped: Manufacturers may use the A/B and +/− labels differently; this is the first thing to check.
  • Missing or excess termination: Signal reflections and random errors.
  • No biasing: The receiver sees random characters while the bus is idle.
  • Driver released too early: The last byte is corrupted, causing a CRC error.
  • Parity and baud rate mismatch: The device does not respond at all.
  • Response timeout too short: The client sends a new request without waiting for the server's response.
  • Ground potential difference: On long runs without isolation, errors and even hardware failures.

Testing Tips

During development, the fastest method is to test the device end to end with a USB–RS485 converter and Modbus client software running on a PC. A logic analyzer's Modbus decoder lets you see the frames and their timing, while looking at the A–B differential voltage on an oscilloscope reveals termination and reflection problems.

Conclusion

A robust Modbus RTU device is the combination of correctly selected and protected RS-485 hardware, correct direction control, specification-compliant timing and a well-documented register map.

As part of our embedded software development service, we develop Modbus RTU and RS-485 communication for STM32-based devices together with the team that designs the hardware. If you need a communication board, take a look at our electronics and PCB design page as well.

Related services

Need Help with This?

Embedded Software Development

Embedded software tailored to your hardware and reliable in the field: written from scratch, or your existing software improved.

Learn more

Electronics and Hardware Design

From requirements to schematic, from PCB design to prototype: control, power, sensor and communication boards.

Learn more

Blog

More Articles

PCB design · 6 min read

EMC in PCB Design: 10 Rules for Preventing Noise from the Start

Ground plane, current loops, decoupling, the switching power stage and connector filtering: 10 rules that prevent EMC problems from the start.

Read the article

Electronics design · 7 min read

The Electronics Design Process: From Idea to Mass Production, Step by Step

From requirements to schematic, from PCB to prototype and mass production: the steps an electronic board goes through and what to watch for at each one.

Read the article

Design review · 5 min read

Pre-production Design Review: The 15 Most Common Mistakes

From schematic to footprints, from layout to manufacturing files: 15 common mistakes to catch before you send a board to production.

Read the article

Let's Write Your Board's Firmware Together.

Tell us briefly about your project; we'll get back to you with the scope, timeline and an estimated budget.