MODBUS_SET_SLAVE(3)

πŸ“¦
version 3.1.6 Β· 3 versions
, in debian bookworm

✨ 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