This project demonstrates how to implement a Modbus RTU slave using the ZModbusRTU library for an microcontroller in the Arduino IDE. It provides basic functionality for reading and writing coil status, holding register, input status and input register values through Modbus communication.
- Modbus RTU slave functionality using the ZModbusRTU library.
- Reading and writing coil status and holding registers.
- Configurable Modbus parameters like baud rate, coil count, register count, input status count, input register count and slave ID.
- ZModbusRTU Library (Installable via Arduino IDE Library Manager)
- Uses
Serial
port for Modbus RTU communication.
-
Install ZModbusRTU Library:
- Open the Arduino IDE.
- Go to Sketch > Include Library > Manage Libraries....
- Search for ZModbusRTU and install it.
-
Upload the Code:
- Copy the provided code into a new Arduino sketch.
- Ensure the board is selected under Tools > Board > (Selecting your board.).
- Select the correct port under Tools > Port > Board's COM port.
-
Compile and Upload the sketch to your Board.
- Baud Rate:
9600 - 115200
(recommend) - Slave ID:
1-255
- Maximum Coil Status:
65535
(Default is 100) - Maximum Input Status:
65535
(Default is 100) - Maximum Holding Registers:
65535
(Default is 100) - Maximum Input Registers:
65535
(Default is 100)
#define SlaveID 4
#define Baudrate 115200
#include <ZModbusRTU.h>
// Create an instance of the ZModbusRTU class
ZModbusRTU modbus(Serial, Baudrate, SlaveID);
void setup(){
modbus.setMaximum(MAX_COILSTATUS,
MAX_INPUTSTATUS,
MAX_HOLDINGREG,
MAX_INPUTREG); //[Optional] (Everyfunctions Default = 100)
modbus.begin();
modbus.setCoilStatusValue(0, 1); // Set coil status address 0 to ON
modbus.setHoldingRegisterValue(0, 123); // Set holding address 0 register to 123
modbus.setWriteRegisterCallback(onWriteRegister); //Call back when update Register value
modbus.setWriteCoilCallback(onWriteCoil); //Call back when update Coil value
}
void loop() {
modbus.handle();
}
void onWriteRegister(uint16_t address, uint16_t value) {
Serial.print("Register written at address: ");
Serial.print(address);
Serial.print(" with value: ");
Serial.println(value);
}
void onWriteCoil(uint16_t address, uint16_t value) {
Serial.print("Coil written at address: ");
Serial.print(address);
Serial.print(" with value: ");
Serial.println(value);
}
modbus.setFetchTimer(16); //Interval between reading each byte (Default = 16ms)
modbus.setdebug(true);//Default = false
- Debug mode will show all data on same
Serial
port. Modbus poll software
will not working.- Using Debug mode via
Serial monitor software
only
This project is licensed under the MIT License.