MODBUS_READ_REGISTER(3)

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

✨ MODBUS_READ_REGISTER(3) ✨

ok so bestie, we're in the libmodbus Manual today and this page is literally about reading a whole lil squad of registers at once. no cap, it's giving "one call, many registers" and honestly? obsessed. πŸŽ€


🌸 NAME 🌸

modbus_read_registers β€” read many registers


πŸ¦‹ SYNOPSIS πŸ¦‹

int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t
*dest);

πŸ’– DESCRIPTION πŸ’–

ok so picture this: modbus_read_registers() shall read the content of the nb holding registers at the address addr of the remote device. the whole result of that reading gets stashed in the dest array as word values, which are 16 bits each. slay. ✨

now listen, and this is the part where you have to be a responsible main character: you must take care to allocate enough memory to store the results in dest β€” at least nb * sizeof(uint16_t). that's the bare minimum. do not skimp. the malloc is not gonna do it for you. πŸ™ˆ

also for the nerds keeping score: this function uses the Modbus function code 0x03 (read holding registers). iconic behaviour, fr fr. πŸ’…


πŸ”₯ RETURN VALUE πŸ”₯

if everything goes good, the function shall return the number of read registers. if not? it shall return -1 and set errno. yeah. that's the vibe check failing. 😭


πŸ’€ ERRORS πŸ’€

  • EMBMDATA β€” Too many registers requested. girl. you asked for too much. 🫢

🌈 EXAMPLE 🌈

here's the whole thing in action, look at her go:

modbus_t *ctx;
uint16_t tab_reg[64];
int rc;
int i;

ctx = modbus_new_tcp("127.0.0.1", 1502);
if (modbus_connect(ctx) == -1) {
    fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno));
    modbus_free(ctx);
    return -1;
}

rc = modbus_read_registers(ctx, 0, 10, tab_reg);
if (rc == -1) {
    fprintf(stderr, "%s\n", modbus_strerror(errno));
    return -1;
}

for (i=0; i < rc; i++) {
    printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]);
}

modbus_close(ctx);
modbus_free(ctx);

not her connecting, reading ten registers, printing them in both decimal and hex, and then cleaning up after herself like a grown-up. we love an organized queen. πŸ‘‘


🧚 SEE ALSO 🧚


πŸ’œ AUTHORS πŸ’œ

The libmodbus documentation was written by StΓ©phane Raimbault <stephane.raimbault@gmail.com> β€” credit where credit is due, periodt. 🌟


ok and before you go, the receipts: this is libmodbus v3.1.6, dated 11/17/2025. go read your registers bestie, ily, drink water πŸ’–πŸŒΈβœ¨

πŸ“¦ where this page comes from