Industrial RTU and ASCII Modbus protocol implementation for embedded systems
Kinematrix provides a complete Modbus implementation supporting both RTU and ASCII modes with master and slave configurations for industrial communication.
Modbus is a widely-used industrial communication protocol designed for reliable data exchange between electronic devices in automation and control systems.
Modbus Slave
Respond to master requests and manage register banks
The Modbus implementation consists of three main classes:
modbusSlave // Communication handler and protocol enginemodbusDevice // Device identity and register bank management modbusRegBank // Data storage and type conversion
// Digital register (1 bit per address)struct modbusDigReg { word address; byte value; // 0 or 1 modbusDigReg *next;};// Analog register (16-bit per address)struct modbusAnaReg { word address; word value; // 0-65535 modbusAnaReg *next;};
class modbusDevice : public modbusRegBank {public: modbusDevice(void); void setId(byte id); // Set device ID (1-247) byte getId(void); // Get device IDprivate: byte _id;};
#define DO 0x00 // Digital Output (Coil)#define DI 0x01 // Digital Input#define AI 0x03 // Analog Input#define AO 0x04 // Analog Output (Holding Register)
#define DEVMAX 10 // Maximum devices on network#define QUEMAX 10 // Maximum control register queue#define SERIALMAXDELAY 100 // Serial wait time (microseconds)#define SERIALBAUD 9600 // Default baud rate
// Digital Coils (0-99)device.add(0); // Emergency stopdevice.add(1); // Motor enabledevice.add(2); // Alarm status// Analog Holding Registers (100-199)device.add(100); // Temperature sensordevice.add(101); // Pressure sensordevice.add(102); // Flow ratedevice.add(103); // Motor speed setpoint// Analog Input Registers (200-299)device.add(200); // Voltage readingdevice.add(201); // Current reading
Modbus typically uses RS-485 for multi-drop networks:
Arduino MAX485 Module TX -------> DI RX <------- RO D2 -------> DE/RE (direction control) 5V -------> VCC GND -------> GNDRS-485 Bus: A <------> A (all devices) B <------> B (all devices)Termination: 120Ω resistor between A and B at both ends
// Add delay after direction changedigitalWrite(DE_PIN, HIGH);delayMicroseconds(50); // Let transceiver settlemodbusSerial.write(buffer, length);modbusSerial.flush();delayMicroseconds(50);digitalWrite(DE_PIN, LOW);
Bus Termination: Always install 120Ω termination resistors at both ends of the RS-485 bus to prevent signal reflections.
Register Organization: Group related registers together and document your register map. This makes debugging and integration much easier.
Timing: Modbus RTU requires specific inter-frame delays. The library handles this automatically, but be aware when debugging timing-critical applications.