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:
1
// Create new mbs instance
2
ModbusSlave mbs(RS485_COM);
Copied!
For RS-232 communication the way of use is very similar.
1
// Create new mbs instance
2
ModbusSlave mbs(RS232_COM);
Copied!

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:
1
{
2
// Modbus slave configuration parameters
3
// SlaveId
4
const unsigned char SLAVE = 2;
5
// Baud rate
6
const long BAUD = 9600;
7
// Configure msb
8
mbs.configure(SLAVE, BAUD);
9
}
Copied!
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:
1
{
2
// Modbus slave configuration parameters
3
// SlaveId
4
const unsigned char SLAVE = 1;
5
// Baud rate
6
const long BAUD = 115200;
7
// Configure msb
8
mbs.configure(SLAVE, BAUD, SOCKET0);
9
}
Copied!
See an example of use here:
Examples
Waspmote

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:
1
// Global buffer
2
int regs[MB_REGS];
3
{
4
// Pass current register values to mbs
5
mbs.update(regs, MB_REGS);
6
7
// Read all the analog Inputs, and store the values in
8
// the Modbus registers
9
regs[MB_0] = ACC.getX();
10
// X Value
11
regs[MB_1] = ACC.getY();
12
// Y Value
13
regs[MB_2] = ACC.getZ();
14
// Z Value
15
regs[MB_3] = PWR.getBatteryLevel(); // Batery level
16
Copied!
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:
Examples
Waspmote
Last modified 1yr ago