2

I'm using the ModbusMaster.h library on a project, with arduino-uno and a TTL/RS-485 converter, and the function has to identify the slave that it is communicating. The slaves goes from 1 to 16. After I've begun the connection,

ModbusMaster node(1);
node.begin(9600);

I have to send a message, and if this massage returns an error, I have to change the slave number, until I got an valid answer. But I didn't find any functions to close this connection, or to delete it, I even have tried,

delete &node;

but it didn't work. I'm trying to close this connection so I could begin another one with another node, because I didn't find a function to change the slave number.

Claudiaum
  • 51
  • 3
  • I see no function to change the `_u8MBSlave` other that the [constructor](https://github.com/4-20ma/ModbusMaster/blob/master/ModbusMaster.cpp#L66). My C isn't great by you might try something like `node = ModbusMaster(2);` – Gerben Mar 09 '15 at 21:03
  • 1
    Generally speaking, you should never call `delete` on something unless you originally created it with `new`. Attempting to delete an object from the stack could cause your program to crash or misbehave in other ways. – Peter Bloomfield Mar 09 '15 at 21:08
  • Indeed that would not work. But why not `ModbusMaster* node = new ModbusMaster(id)`, then send, check for error, if so `delete *node`, `++id`, repeat? Not the most efficient, but simple. (You could also add a function to change the id to the library.) – fuenfundachtzig Mar 09 '15 at 21:57
  • Gerben, it didn't work, =/. Thanks for the tip Peter. Fuenfundachtzig, how do you pronunciate that? O.o, but it didn't work either. But to solve, I had to create a function that keep creating another nodes, and every time it made a new node, it'll send a request, and if the request was an error, it passes to create another node, if the answer was a success, it would made: `ModbusMaster node4(4)` "if the success was on the 4th try", then: `node4.begin(); node = node4;` – Claudiaum Mar 12 '15 at 19:27

1 Answers1

2

Maybe this question is too old and the API has changed, so my answer is reference.

The ModbusMaster constructor does not accept parameters.

From reading the source code, the method begin(uint8_t slave, Stream &serial) just initializes variables and can be called again with a new slave value without the need to destroy the ModbusMaster object.

Reference:

[1] https://github.com/4-20ma/ModbusMaster/blob/master/src/ModbusMaster.cpp, line 61.