| 1 | # modbus_read_registers |
| 2 | |
| 3 | ## Name |
| 4 | |
| 5 | modbus_read_registers - read many registers |
| 6 | |
| 7 | ## Synopsis |
| 8 | |
| 9 | ```c |
| 10 | int modbus_read_registers(modbus_t *ctx, int addr, int nb, uint16_t *dest); |
| 11 | ``` |
| 12 | |
| 13 | ## Description |
| 14 | |
| 15 | The *modbus_read_registers()* function shall read the content of the `nb` |
| 16 | holding registers to the address `addr` of the remote device. The result of |
| 17 | reading is stored in `dest` array as word values (16 bits). |
| 18 | |
| 19 | The `dest` array must be allocated with at least `nb * sizeof(uint16_t)` bytes. |
| 20 | It is the caller's responsibility to ensure the buffer is large enough to hold |
| 21 | all the registers to be read. |
| 22 | |
| 23 | The function uses the Modbus function code 0x03 (read holding registers). |
| 24 | |
| 25 | ## Return value |
| 26 | |
| 27 | The function shall return the number of read registers |
| 28 | if successful. Otherwise it shall return -1 and set errno. |
| 29 | |
| 30 | ## Errors |
| 31 | |
| 32 | - *EINVAL*, the `ctx` or `dest` argument is NULL, or `nb` is less than 1. |
| 33 | - *EMBXILVAL*, too many registers requested (nb > MODBUS_MAX_READ_REGISTERS). |
| 34 | |
| 35 | ## Example |
| 36 | |
| 37 | ```c |
| 38 | modbus_t *ctx; |
| 39 | uint16_t tab_reg[64]; |
| 40 | int rc; |
| 41 | int i; |
| 42 | |
| 43 | ctx = modbus_new_tcp("127.0.0.1", 502); |
| 44 | if (modbus_connect(ctx) == -1) { |
| 45 | fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno)); |
| 46 | modbus_free(ctx); |
| 47 | return -1; |
| 48 | } |
| 49 | |
| 50 | rc = modbus_read_registers(ctx, 0, 10, tab_reg); |
| 51 | if (rc == -1) { |
| 52 | fprintf(stderr, "%s\n", modbus_strerror(errno)); |
| 53 | return -1; |
| 54 | } |
| 55 | |
| 56 | for (i=0; i < rc; i++) { |
| 57 | printf("reg[%d]=%d (0x%X)\n", i, tab_reg[i], tab_reg[i]); |
| 58 | } |
| 59 | |
| 60 | modbus_close(ctx); |
| 61 | modbus_free(ctx); |
| 62 | ``` |
| 63 | |
| 64 | ## See also |
| 65 | |
| 66 | - [modbus_write_register](modbus_write_register.md) |
| 67 | - [modbus_write_registers](modbus_write_registers.md) |