Skip to content

ModbusRTU

Path: src/modbusRTU.h

Revision History: Initial documentation

ModbusRTU is a comprehensive implementation of the Modbus RTU protocol over RS-485 for ESP32 devices. It provides a robust, industrial-grade solution for bidirectional communication between master and slave devices, supporting both master functionality for querying other devices and slave functionality for responding to external queries.

  • Hardware:

    • RS-485 transceiver (e.g., MAX485)
    • RX pin (configured in pins_arduino.h)
    • TX pin (configured in pins_arduino.h)
    • DE/RE pin for RS-485 direction control
  • Software:

    • Platform.io with ESP32 support
    • C17 compiler support
  • Supports both Modbus master and slave functionalities
  • Implements standard Modbus function codes (3, 4, 6, 16)
  • Automatic CRC calculation and validation
  • Configurable timeouts and retry mechanisms
  • Interrupt-driven communication with hardware buffer
  • Thread-safe operation
  • Extensible register mapping system
  • Support for various data types (uint16_t, float, etc.)

ModbusRTU

Component

ArduinoLog

Send Request/Response

Master Mode

Slave Mode

Receive Response

No Response

Success/Error

Retries Left

Max Retries

Idle

Transmitting

Waiting

Processing

Timeout

Retry

  • Consider implementing a more efficient buffer management system to reduce memory usage
  • Optimize CRC calculation for speed using lookup tables
  • Evaluate interrupt priorities to ensure timely processing of incoming data
  • Implement message authentication to prevent unauthorized commands
  • Add support for encrypted Modbus communication where security is critical
  • Consider implementing access control lists for sensitive register operations
  • Complete full compliance with Modbus RTU specification
  • Add support for additional function codes as needed for specific applications
  • Ensure timing requirements meet the Modbus specification under all operating conditions
  • Use shielded twisted pair cables for RS-485 communication to maximize reliability
  • Implement proper line termination (120Ω) at both ends of the RS-485 bus
  • Consider using galvanic isolation for the RS-485 transceiver in noisy environments
  • Regularly test communication with various slave devices to ensure compatibility

This example shows how to initialize and mount the ModbusRTU component in master mode:

#ifdef PIN_RS485_DE
modbus = new ModbusRTU(
this, // owner
SERIAL_RS485, // serial port (defined in pins_arduino.h)
PIN_RS485_DE, // direction control pin
MODBUS_BAUD_RATE, // baud rate (typically 9600, 19200, or 115200)
SERIAL_8N1, // data format (8 bits, no parity, 1 stop bit)
1 // device ID for slave mode
);
if (modbus)
{
components.push_back(modbus);
Log.infoln(F("ModbusRTU initialized. DE/RE Pin: %d, Baud: %d, ID: %d"),
PIN_RS485_DE, MODBUS_BAUD_RATE, 1);
}
else
{
Log.errorln(F("ModbusRTU initialization failed."));
}
#endif