Skip to content

Modbus485 Component

Path: src/modbus485.h

Revision History:

  • Initial documentation

A robust Modbus RTU communication component supporting RS-485 electrical interface for ESP-32 devices. This implementation features comprehensive error handling, logging, and state management, making it suitable for industrial applications requiring reliable communication.

  • Hardware:
    • RS-485 transceiver (e.g., MAX485)
    • UART TX pin
    • UART RX pin
    • DE/RE pin for direction control
  • Software:
    • HardwareSerial
    • ArduinoLog or similar for logging
  • Full Modbus RTU master client implementation
  • Configurable baud rate, parity, and stop bits
  • Support for multiple read and write function codes
  • Automatic transaction ID management
  • Comprehensive error handling and reporting
  • Response timeout management
  • Debug logging
  • Modbus frame validation (CRC16)
  • State machine design for reliable operation
  • Supports single and block operations for coils, discrete inputs, holding registers and input registers

Modbus485

Component

EventManager

ArduinoLog

request initiated

line ready

frame sent

response received

timeout

success

validation failed

reset

reset

IDLE

WAITING_TO_SEND

SENDING

WAITING_FOR_RESPONSE

PROCESSING_RESPONSE

TIMEOUT_ERROR

ERROR

  • Consider implementing a response parser to handle partial responses
  • Add transaction queuing to handle multiple concurrent requests
  • Optimize memory usage for constrained devices
  • Add retry mechanism for failed requests
  • Implement message authentication for critical operations
  • Consider encryption for sensitive data transmission
  • Add access control mechanisms for write operations
  • Implement session timeouts for maintaining connection state
  • Ensure full compliance with Modbus RTU specification
  • Validate against Modbus conformance test suite
  • Document compatibility with specific Modbus devices
  • Use proper shielded cables for RS-485 communication
  • Implement proper termination resistors on the RS-485 bus
  • Consider using optically isolated RS-485 transceivers in noisy environments
  • Monitor response times and adjust timeouts accordingly
  • Implement application-level heartbeats for critical connections
#ifdef PIN_RS485_DE
modbus485 = new Modbus485(
this, // owner
PIN_RS485_TX, // TX pin
PIN_RS485_RX, // RX pin
PIN_RS485_DE, // DE/RE pin
RS485_BAUDRATE, // baud rate
RS485_CONFIG // UART configuration
);
if (modbus485) {
components.push_back(modbus485);
Log.infoln(F("Modbus485 initialized. TX:%d, RX:%d, DE:%d, Baud:%d"),
PIN_RS485_TX, PIN_RS485_RX, PIN_RS485_DE, RS485_BAUDRATE);
} else {
Log.errorln(F("Modbus485 initialization failed."));
}
#endif