| 1 | # modbus_set_slave |
| 2 | |
| 3 | ## Name |
| 4 | |
| 5 | modbus_set_slave - set slave number in the context |
| 6 | |
| 7 | ## Synopsis |
| 8 | |
| 9 | ```c |
| 10 | int modbus_set_slave(modbus_t *ctx, int slave); |
| 11 | ``` |
| 12 | |
| 13 | ## Description |
| 14 | |
| 15 | The *modbus_set_slave()* function shall set the slave number in the libmodbus |
| 16 | context. |
| 17 | |
| 18 | It is usually only required to set the slave ID in **RTU**. The meaning of this |
| 19 | ID will be different if your program acts as client (master) or server (slave). |
| 20 | |
| 21 | As **RTU client**, *modbus_set_slave()* sets the ID of the remote device you |
| 22 | want to communicate. Be sure to set the slave ID before issuing any Modbus |
| 23 | requests on the serial bus. If you communicate with several servers (slaves), |
| 24 | you can set the slave ID of the remote device before each request. |
| 25 | |
| 26 | As **RTU server**, the slave ID allows the various clients to reach your |
| 27 | service. You should use a free ID, once set, this ID should be known by the |
| 28 | clients of the network. According to the protocol, a Modbus device must only |
| 29 | accept message holding its slave number or the special broadcast number. |
| 30 | |
| 31 | In **TCP**, the slave number is only required if the message must reach a device |
| 32 | on a serial network. Some not compliant devices or software (such as modpoll) |
| 33 | uses the slave ID as unit identifier, that's incorrect (cf page 23 of Modbus |
| 34 | Messaging Implementation Guide v1.0b) but without the slave value, the faulty |
| 35 | remote device or software drops the requests! The special value |
| 36 | `MODBUS_TCP_SLAVE` (0xFF) can be used in TCP mode to restore the default value. |
| 37 | |
| 38 | The broadcast address is `MODBUS_BROADCAST_ADDRESS`. This special value must be |
| 39 | use when you want all Modbus devices of the network receive the request. |
| 40 | |
| 41 | ## Return value |
| 42 | |
| 43 | The function shall return 0 if successful. Otherwise it shall return -1 and set |
| 44 | errno to one of the values defined below. |
| 45 | |
| 46 | ## Errors |
| 47 | |
| 48 | - *EINVAL*, the slave number is invalid. |
| 49 | |
| 50 | ## Example |
| 51 | |
| 52 | ```c |
| 53 | modbus_t *ctx; |
| 54 | |
| 55 | ctx = modbus_new_rtu("/dev/ttyUSB0", 115200, 'N', 8, 1); |
| 56 | if (ctx == NULL) { |
| 57 | fprintf(stderr, "Unable to create the libmodbus context\n"); |
| 58 | return -1; |
| 59 | } |
| 60 | |
| 61 | rc = modbus_set_slave(ctx, YOUR_DEVICE_ID); |
| 62 | if (rc == -1) { |
| 63 | fprintf(stderr, "Invalid slave ID\n"); |
| 64 | modbus_free(ctx); |
| 65 | return -1; |
| 66 | } |
| 67 | |
| 68 | if (modbus_connect(ctx) == -1) { |
| 69 | fprintf(stderr, "Connection failed: %s\n", modbus_strerror(errno)); |
| 70 | modbus_free(ctx); |
| 71 | return -1; |
| 72 | } |
| 73 | ``` |
| 74 | |
| 75 | ## See also |
| 76 | |
| 77 | - [modbus_get_slave](modbus_get_slave.md) |