Slave library functions

The configuration of the slave is very important before starting the communication with the master device.

Library constructor

Before using the library, an object of the library must be created. This object is necessary for managing the rest of the functions.

Example of use for the RS-485 module:

// Create new mbs instance
ModbusSlave mbs(RS485_COM);

For RS-232 communication the way of use is very similar.

// Create new mbs instance
ModbusSlave mbs(RS232_COM);

Configuring the slave

This function is used to configure some necessary parameters of the network. This function will assign the baud rate and the slave direction that the master will use to communicate with the slave in a network.

For RS-485:

{
// Modbus slave configuration parameters
// SlaveId
const unsigned char SLAVE = 2;
// Baud rate
const long BAUD = 9600;
// Configure msb
mbs.configure(SLAVE, BAUD);
}

In RS-232 the use is very similar, but you have to configure the socket where the module is connected in the configuration function.

Example of use:

{
// Modbus slave configuration parameters
// SlaveId
const unsigned char SLAVE = 1;
// Baud rate
const long BAUD = 115200;
// Configure msb
mbs.configure(SLAVE, BAUD, SOCKET0);
}

See an example of use here:

Saving data in registers

To use Waspmote as a Modbus slave device you need create some specific registers to exchange information. These registers are used to read or write the information sent by the master device, depending on the operation. Waspmote slave library only accepts the next Modbus functions:

Code function

Function name

0x03

Read Holding Registers

0x06

Write Single Register

0x10

Write Multiple Registers

These registers can be used to store information, for example from the sensors connected to Waspmote.

Example of use:

// Global buffer
int regs[MB_REGS];
{
// Pass current register values to mbs
mbs.update(regs, MB_REGS);
// Read all the analog Inputs, and store the values in
// the Modbus registers
regs[MB_0] = ACC.getX();
// X Value
regs[MB_1] = ACC.getY();
// Y Value
regs[MB_2] = ACC.getZ();
// Z Value
regs[MB_3] = PWR.getBatteryLevel(); // Batery level
‚Äč

The function updates the current values of the registers in the Modbus slave object. These registers can also be written from the master device and used for example, to activate a digital output or to configure some parameters of the slave.

This function is useful for controlling what values the user wants to make available for the master.

See an example of use here: