MODBUS_SET_SLAVE(3)
β¨ MODBUS_SET_SLAVE(3) β¨
libmodbus Manual π bestie you're in the right place, this is the modbus_set_slave page and it's literally so useful
πΈ NAME πΈ
modbus_set_slave β set the slave number in the context π
π¦ SYNOPSIS π¦
int modbus_set_slave(modbus_t *ctx, int slave);
π DESCRIPTION π
okay so the modbus_set_slave() function shall set the slave number in the libmodbus context. no cap, that's the whole job.
The way it behaves depends on the network and on what role the device is playing, so let's break it down:
π RTU
This defines the slave ID of the remote device you wanna talk to in master mode, or it sets the internal slave ID when you're in slave mode. Per the protocol, a Modbus device must only accept a message that's holding its slave number or the special broadcast number. that's just how the protocol works, periodt.
β TCP
In TCP, the slave number is only required if the message needs to reach a device on a serial network. Some not-compliant devices or software (looking at you, modpoll π) use the slave ID as the unit identifier, which is incorrect (cf page 23 of Modbus Messaging Implementation Guide v1.0b) but without the slave value, the faulty remote device or software drops the requests! π The special value MODBUS_TCP_SLAVE (0xFF) can be used in TCP mode to restore the default value. iconic.
The broadcast address is MODBUS_BROADCAST_ADDRESS. This special value must be used when you want all Modbus devices on the network to receive the request. everybody gets the message, no one is left out π
π RETURN VALUE π
The function shall return 0 if successful. Otherwise it shall return -1 and set errno to one of the values defined below. simple as that bestie.
π₯ ERRORS π₯
EINVALβ the slave number is invalid. nope, not valid, try again π
π EXAMPLE π
modbus_t *ctx;
ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1);
if (ctx == NULL) {
fprintf(stderr, "Unable to create the libmodbus context\n");
return -1;
}
rc = modbus_set_slave(ctx, YOUR_DEVICE_ID);
if (rc == -1) {
fprintf(stderr, "Invalid slave ID\n");
modbus_free(ctx);
return -1;
}
if (modbus_connect(ctx) == -1) {
fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
modbus_free(ctx);
return -1;
}
π§ SEE ALSO π§
π AUTHORS π
The libmodbus documentation was written by StΓ©phane Raimbault <stephane.raimbault@gmail.com>
and that's the whole page, bestie!! π«Ά this was libmodbus v3.1.6, dated 11/17/2025 β¨ go forth and set those slave numbers, you've got this π π
π¦ where this page comes from
- debian bookworm: libmodbus-dev 3.1.6-2.1+deb12u1 Β· LGPL-2.1-or-later
- π girlified by deepseek-ai/DeepSeek-V4.1-Flash on : a language model's rewrite of the original, under its terms